3 input#modalInfo.modal(type="checkbox")
6 data-checkbox="modalInfo"
9 label.modal-close(for="modalInfo")
10 p(v-html="infoMessage")
11 input#modalChat.modal(
13 @click="resetChatColor()"
17 data-checkbox="modalChat"
20 label.modal-close(for="modalChat")
22 span {{ st.tr["Participant(s):"] }}
24 v-for="p in Object.values(people)"
25 v-if="p.focus && !!p.name"
29 v-if="Object.values(people).some(p => p.focus && !p.name)"
34 :players="game.players"
35 :pastChats="game.chats"
38 @chatcleared="clearChat"
40 input#modalConfirm.modal(type="checkbox")
41 div#confirmDiv(role="dialog")
44 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
48 span {{ st.tr["Move played:"] + " " }}
49 span.bold {{ moveNotation }}
51 span {{ st.tr["Are you sure?"] }}
52 .button-group#buttonsConfirm
53 // onClick for acceptBtn: set dynamically
55 span {{ st.tr["Validate"] }}
56 button.refuseBtn(@click="cancelMove()")
57 span {{ st.tr["Cancel"] }}
59 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
60 span.variant-cadence {{ game.cadence }}
61 span.variant-name {{ game.vname }}
63 v-if="nextIds.length > 0"
64 @click="showNextGame()"
66 | {{ st.tr["Next_g"] }}
67 button#chatBtn.tooltip(
68 onClick="window.doClick('modalChat')"
71 img(src="/images/icons/chat.svg")
72 #actions(v-if="game.score=='*'")
75 :class="{['draw-' + drawOffer]: true}"
76 :aria-label="st.tr['Draw']"
78 img(src="/images/icons/draw.svg")
82 :aria-label="st.tr['Abort']"
84 img(src="/images/icons/abort.svg")
88 :aria-label="st.tr['Resign']"
90 img(src="/images/icons/resign.svg")
92 v-else-if="!!game.mycolor"
93 @click="clickRematch()"
94 :class="{['rematch-' + rematchOffer]: true}"
95 :aria-label="st.tr['Rematch']"
97 img(src="/images/icons/rematch.svg")
100 span.name(:class="{connected: isConnected(0)}")
101 | {{ game.players[0].name || "@nonymous" }}
103 v-if="game.score=='*'"
104 :class="{yourturn: !!vr && vr.turn == 'w'}"
106 span.time-left {{ virtualClocks[0][0] }}
107 span.time-separator(v-if="!!virtualClocks[0][1]") :
108 span.time-right(v-if="!!virtualClocks[0][1]")
109 | {{ virtualClocks[0][1] }}
111 span.name(:class="{connected: isConnected(1)}")
112 | {{ game.players[1].name || "@nonymous" }}
114 v-if="game.score=='*'"
115 :class="{yourturn: !!vr && vr.turn == 'b'}"
117 span.time-left {{ virtualClocks[1][0] }}
118 span.time-separator(v-if="!!virtualClocks[1][1]") :
119 span.time-right(v-if="!!virtualClocks[1][1]")
120 | {{ virtualClocks[1][1] }}
124 @newmove="processMove"
129 import BaseGame from "@/components/BaseGame.vue";
130 import Chat from "@/components/Chat.vue";
131 import { store } from "@/store";
132 import { GameStorage } from "@/utils/gameStorage";
133 import { ppt } from "@/utils/datetime";
134 import { ajax } from "@/utils/ajax";
135 import { extractTime } from "@/utils/timeControl";
136 import { getRandString } from "@/utils/alea";
137 import { getScoreMessage } from "@/utils/scoring";
138 import { getFullNotation } from "@/utils/notation";
139 import { getDiagram } from "@/utils/printDiagram";
140 import { processModalClick } from "@/utils/modalClick";
141 import { playMove, getFilteredMove } from "@/utils/playUndo";
142 import { ArrayFun } from "@/utils/array";
143 import params from "@/parameters";
154 // rid = remote (socket) ID
159 game: {}, //passed to BaseGame
160 // virtualClocks will be initialized from true game.clocks
162 vr: null, //"variant rules" object initialized from FEN
165 people: {}, //players + observers
166 onMygames: [], //opponents (or me) on "MyGames" page
167 lastate: undefined, //used if opponent send lastate before game is ready
168 repeat: {}, //detect position repetition
169 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.gameRef.id = to.params["id"];
206 this.gameRef.rid = to.query["rid"];
207 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
212 // NOTE: some redundant code with Hall.vue (mostly related to people array)
213 created: function() {
216 mounted: function() {
217 document.addEventListener('visibilitychange', this.visibilityChange);
219 .getElementById("chatWrap")
220 .addEventListener("click", processModalClick);
221 if ("ontouchstart" in window) {
222 // Disable tooltips on smartphones:
223 document.getElementsByClassName("tooltip").forEach(elt => {
224 elt.classList.remove("tooltip");
228 beforeDestroy: function() {
229 document.removeEventListener('visibilitychange', this.visibilityChange);
230 this.cleanBeforeDestroy();
233 visibilityChange: function() {
234 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
236 document.visibilityState == "visible"
241 atCreation: function() {
242 // 0] (Re)Set variables
243 this.gameRef.id = this.$route.params["id"];
244 // rid = remote ID to find an observed live game,
245 // next = next corr games IDs to navigate faster
246 // (Both might be undefined)
247 this.gameRef.rid = this.$route.query["rid"];
248 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
249 // Always add myself to players' list
250 const my = this.st.user;
261 players: [{ name: "" }, { name: "" }],
265 let chatComp = this.$refs["chatcomp"];
266 if (!!chatComp) chatComp.chats = [];
267 this.virtualClocks = [[0,0], [0,0]];
270 this.rematchOffer = "";
272 this.lastate = undefined;
274 this.roomInitialized = false;
275 this.askGameTime = 0;
276 this.gameIsLoading = false;
277 this.gotLastate = false;
278 this.gotMoveIdx = -1;
279 this.opponentGotMove = false;
280 this.askLastate = null;
281 this.retrySendmove = null;
282 this.clockUpdate = null;
283 this.newConnect = {};
285 // 1] Initialize connection
286 this.connexionString =
293 // Discard potential "/?next=[...]" for page indication:
294 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
295 this.conn = new WebSocket(this.connexionString);
296 this.conn.onmessage = this.socketMessageListener;
297 this.conn.onclose = this.socketCloseListener;
298 // Socket init required before loading remote game:
299 const socketInit = callback => {
300 if (!!this.conn && this.conn.readyState == 1)
304 // Socket not ready yet (initial loading)
305 // NOTE: it's important to call callback without arguments,
306 // otherwise first arg is Websocket object and loadGame fails.
307 this.conn.onopen = () => callback();
309 if (!this.gameRef.rid)
310 // Game stored locally or on server
311 this.loadGame(null, () => socketInit(this.roomInit));
313 // Game stored remotely: need socket to retrieve it
314 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
315 // --> It will be given when receiving "fullgame" socket event.
316 socketInit(this.loadGame);
318 cleanBeforeDestroy: function() {
319 if (!!this.askLastate)
320 clearInterval(this.askLastate);
321 if (!!this.retrySendmove)
322 clearInterval(this.retrySendmove);
323 if (!!this.clockUpdate)
324 clearInterval(this.clockUpdate);
325 this.send("disconnect");
327 roomInit: function() {
328 if (!this.roomInitialized) {
329 // Notify the room only now that I connected, because
330 // messages might be lost otherwise (if game loading is slow)
331 this.send("connect");
332 this.send("pollclients");
333 // We may ask fullgame several times if some moves are lost,
334 // but room should be init only once:
335 this.roomInitialized = true;
338 send: function(code, obj) {
340 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
342 isConnected: function(index) {
343 const player = this.game.players[index];
344 // Is it me ? In this case no need to bother with focus
345 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
346 // Still have to check for name (because of potential multi-accounts
347 // on same browser, although this should be rare...)
348 return (!this.st.user.name || this.st.user.name == player.name);
349 // Try to find a match in people:
353 Object.keys(this.people).some(sid =>
354 sid == player.sid && this.people[sid].focus)
359 Object.values(this.people).some(p =>
360 p.id == player.uid && p.focus)
364 getOppsid: function() {
365 let oppsid = this.game.oppsid;
367 oppsid = Object.keys(this.people).find(
368 sid => this.people[sid].id == this.game.oppid
371 // oppsid is useful only if opponent is online:
372 if (!!oppsid && !!this.people[oppsid]) return oppsid;
375 resetChatColor: function() {
376 // TODO: this is called twice, once on opening an once on closing
377 document.getElementById("chatBtn").classList.remove("somethingnew");
379 processChat: function(chat) {
380 this.send("newchat", { data: chat });
381 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
382 if (this.game.type == "corr" && this.st.user.id > 0)
383 this.updateCorrGame({ chat: chat });
385 clearChat: function() {
386 // Nothing more to do if game is live (chats not recorded)
387 if (this.game.type == "corr") {
388 if (!!this.game.mycolor) {
392 { data: { gid: this.game.id } }
395 this.$set(this.game, "chats", []);
398 // Notify turn after a new move (to opponent and me on MyGames page)
399 notifyTurn: function(sid) {
400 const player = this.people[sid];
401 const colorIdx = this.game.players.findIndex(
402 p => p.sid == sid || p.uid == player.id);
403 const color = ["w","b"][colorIdx];
404 const movesCount = this.game.moves.length;
406 (color == "w" && movesCount % 2 == 0) ||
407 (color == "b" && movesCount % 2 == 1);
408 this.send("turnchange", { target: sid, yourTurn: yourTurn });
410 showNextGame: function() {
411 // Did I play in current game? If not, add it to nextIds list
412 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
413 this.nextIds.unshift(this.game.id);
414 const nextGid = this.nextIds.pop();
416 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
418 askGameAgain: function() {
419 this.gameIsLoading = true;
420 const currentUrl = document.location.href;
421 const doAskGame = () => {
422 if (document.location.href != currentUrl) return; //page change
423 if (!this.gameRef.rid)
424 // This is my game: just reload.
427 // Just ask fullgame again (once!), this is much simpler.
428 // If this fails, the user could just reload page :/
429 this.send("askfullgame", { target: this.gameRef.rid });
431 // Delay of at least 2s between two game requests
432 const now = Date.now();
433 const delay = Math.max(2000 - (now - this.askGameTime), 0);
434 this.askGameTime = now;
435 setTimeout(doAskGame, delay);
437 socketMessageListener: function(msg) {
438 if (!this.conn) return;
439 const data = JSON.parse(msg.data);
442 data.sockIds.forEach(sid => {
443 if (sid != this.st.user.sid) {
444 this.people[sid] = { focus: true };
445 this.send("askidentity", { target: sid });
450 if (!this.people[data.from]) {
451 this.people[data.from] = { focus: true };
452 this.newConnect[data.from] = true; //for self multi-connects tests
453 this.send("askidentity", { target: data.from });
457 this.$delete(this.people, data.from);
460 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
461 // Either me (another tab) or opponent
462 const sid = data.from;
463 if (!this.onMygames.some(s => s == sid))
465 this.onMygames.push(sid);
466 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
469 if (!this.people[sid])
470 this.send("askidentity", { target: sid });
473 ArrayFun.remove(this.onMygames, sid => sid == data.from);
476 let player = this.people[data.from];
479 this.$forceUpdate(); //TODO: shouldn't be required
484 let player = this.people[data.from];
486 player.focus = false;
487 this.$forceUpdate(); //TODO: shouldn't be required
492 // I logged in elsewhere:
494 alert(this.st.tr["New connexion detected: tab now offline"]);
496 case "askidentity": {
497 // Request for identification
499 // Decompose to avoid revealing email
500 name: this.st.user.name,
501 sid: this.st.user.sid,
504 this.send("identity", { data: me, target: data.from });
508 const user = data.data;
509 let player = this.people[user.sid];
510 // player.focus is already set
511 player.name = user.name;
513 this.$forceUpdate(); //TODO: shouldn't be required
514 // If I multi-connect, kill current connexion if no mark (I'm older)
515 if (this.newConnect[user.sid]) {
518 user.id == this.st.user.id &&
519 user.sid != this.st.user.sid &&
520 !this.killed[this.st.user.sid]
522 this.send("killme", { sid: this.st.user.sid });
523 this.killed[this.st.user.sid] = true;
525 delete this.newConnect[user.sid];
527 if (!this.killed[this.st.user.sid]) {
528 // Ask potentially missed last state, if opponent and I play
530 !!this.game.mycolor &&
531 this.game.type == "live" &&
532 this.game.score == "*" &&
533 this.game.players.some(p => p.sid == user.sid)
535 this.send("asklastate", { target: user.sid });
537 this.askLastate = setInterval(
539 // Ask at most 3 times:
540 // if no reply after that there should be a network issue.
544 !!this.people[user.sid]
546 this.send("asklastate", { target: user.sid });
549 clearInterval(this.askLastate);
559 // Send current (live) game if not asked by any of the players
561 this.game.type == "live" &&
562 this.game.players.every(p => p.sid != data.from[0])
567 players: this.game.players,
569 cadence: this.game.cadence,
570 score: this.game.score,
571 rid: this.st.user.sid //useful in Hall if I'm an observer
573 this.send("game", { data: myGame, target: data.from });
577 const gameToSend = Object.keys(this.game)
580 "id","fen","players","vid","cadence","fenStart","vname",
581 "moves","clocks","initime","score","drawOffer","rematchOffer"
585 obj[k] = this.game[k];
590 this.send("fullgame", { data: gameToSend, target: data.from });
593 // Callback "roomInit" to poll clients only after game is loaded
594 this.loadGame(data.data, this.roomInit);
597 // Sending informative last state if I played a move or score != "*"
599 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
600 this.game.score != "*" ||
601 this.drawOffer == "sent" ||
602 this.rematchOffer == "sent"
604 // Send our "last state" informations to opponent
605 const L = this.game.moves.length;
606 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
608 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
609 clock: this.game.clocks[myIdx],
610 // Since we played a move (or abort or resign),
611 // only drawOffer=="sent" is possible
612 drawSent: this.drawOffer == "sent",
613 rematchSent: this.rematchOffer == "sent",
614 score: this.game.score,
615 score: this.game.scoreMsg,
617 initime: this.game.initime[1 - myIdx] //relevant only if I played
619 this.send("lastate", { data: myLastate, target: data.from });
621 this.send("lastate", { data: {nothing: true}, target: data.from });
625 // Got opponent infos about last move
626 this.gotLastate = true;
627 if (!data.data.nothing) {
628 this.lastate = data.data;
629 if (this.game.rendered)
630 // Game is rendered (Board component)
631 this.processLastate();
632 // Else: will be processed when game is ready
637 const movePlus = data.data;
638 const movesCount = this.game.moves.length;
639 if (movePlus.index > movesCount) {
640 // This can only happen if I'm an observer and missed a move.
641 if (this.gotMoveIdx < movePlus.index)
642 this.gotMoveIdx = movePlus.index;
643 if (!this.gameIsLoading) this.askGameAgain();
647 movePlus.index < movesCount ||
648 this.gotMoveIdx >= movePlus.index
650 // Opponent re-send but we already have the move:
651 // (maybe he didn't receive our pingback...)
652 this.send("gotmove", {data: movePlus.index, target: data.from});
654 this.gotMoveIdx = movePlus.index;
655 const receiveMyMove = (movePlus.color == this.game.mycolor);
656 if (!receiveMyMove && !!this.game.mycolor)
657 // Notify opponent that I got the move:
658 this.send("gotmove", {data: movePlus.index, target: data.from});
659 if (movePlus.cancelDrawOffer) {
660 // Opponent refuses draw
662 // NOTE for corr games: drawOffer reset by player in turn
664 this.game.type == "live" &&
665 !!this.game.mycolor &&
668 GameStorage.update(this.gameRef.id, { drawOffer: "" });
671 this.$refs["basegame"].play(movePlus.move, "received", null, true);
675 clock: movePlus.clock,
676 receiveMyMove: receiveMyMove
684 this.opponentGotMove = true;
685 // Now his clock starts running:
686 const oppIdx = ['w','b'].indexOf(this.vr.turn);
687 this.game.initime[oppIdx] = Date.now();
692 const score = data.side == "b" ? "1-0" : "0-1";
693 const side = data.side == "w" ? "White" : "Black";
694 this.gameOver(score, side + " surrender");
697 this.gameOver("?", "Stop");
700 this.gameOver("1/2", data.data);
703 // NOTE: observers don't know who offered draw
704 this.drawOffer = "received";
707 // NOTE: observers don't know who offered rematch
708 this.rematchOffer = data.data ? "received" : "";
711 // A game started, redirect if I'm playing in
712 const gameInfo = data.data;
714 gameInfo.players.some(p =>
715 p.sid == this.st.user.sid || p.uid == this.st.user.id)
717 this.$router.push("/game/" + gameInfo.id);
720 if (gameInfo.cadence.indexOf('d') === -1) {
722 // Select sid of any of the online players:
724 gameInfo.players.forEach(p => {
725 if (!!this.people[p.sid]) onlineSid.push(p.sid);
727 urlRid += onlineSid[Math.floor(Math.random() * onlineSid.length)];
730 this.st.tr["Rematch in progress:"] +
731 " <a href='#/game/" +
732 gameInfo.id + urlRid +
735 gameInfo.id + urlRid +
737 document.getElementById("modalInfo").checked = true;
742 this.newChat = data.data;
743 if (!document.getElementById("modalChat").checked)
744 document.getElementById("chatBtn").classList.add("somethingnew");
748 socketCloseListener: function() {
749 this.conn = new WebSocket(this.connexionString);
750 this.conn.addEventListener("message", this.socketMessageListener);
751 this.conn.addEventListener("close", this.socketCloseListener);
753 updateCorrGame: function(obj, callback) {
759 gid: this.gameRef.id,
763 if (!!callback) callback();
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 clickRematch: function() {
814 if (!this.game.mycolor) return; //I'm just spectator
815 if (this.rematchOffer == "received") {
818 id: getRandString(), //ignored if corr
819 fen: V.GenRandInitFen(this.game.randomness),
820 players: this.game.players.reverse(),
822 cadence: this.game.cadence
824 let oppsid = this.getOppsid(); //may be null
825 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
826 if (this.game.type == "live") {
827 const game = Object.assign(
831 // (other) Game infos: constant
832 fenStart: gameInfo.fen,
833 vname: this.game.vname,
835 // Game state (including FEN): will be updated
837 clocks: [-1, -1], //-1 = unstarted
838 initime: [0, 0], //initialized later
842 GameStorage.add(game, (err) => {
843 // No error expected.
845 if (this.st.settings.sound)
846 new Audio("/sounds/newgame.flac").play().catch(() => {});
847 this.$router.push("/game/" + gameInfo.id);
857 // cid is useful to delete the challenge:
858 data: { gameInfo: gameInfo },
859 success: (response) => {
860 gameInfo.id = response.gameId;
861 this.$router.push("/game/" + response.gameId);
866 } else if (this.rematchOffer == "") {
867 this.rematchOffer = "sent";
868 this.send("rematchoffer", { data: true });
869 if (this.game.type == "live") {
872 { rematchOffer: this.game.mycolor }
874 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
875 } else if (this.rematchOffer == "sent") {
876 // Toggle rematch offer (on --> off)
877 this.rematchOffer = "";
878 this.send("rematchoffer", { data: false });
879 if (this.game.type == "live") {
884 } else this.updateCorrGame({ rematchOffer: 'n' });
887 abortGame: function() {
888 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
889 this.gameOver("?", "Stop");
893 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
895 this.send("resign", { data: this.game.mycolor });
896 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
897 const side = this.game.mycolor == "w" ? "White" : "Black";
898 this.gameOver(score, side + " surrender");
900 // 3 cases for loading a game:
901 // - from indexedDB (running or completed live game I play)
902 // - from server (one correspondance game I play[ed] or not)
903 // - from remote peer (one live game I don't play, finished or not)
904 loadGame: function(game, callback) {
905 const afterRetrieval = async game => {
906 const vModule = await import("@/variants/" + game.vname + ".js");
907 window.V = vModule.VariantRules;
908 this.vr = new V(game.fen);
909 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
910 const tc = extractTime(game.cadence);
911 const myIdx = game.players.findIndex(p => {
912 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
914 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
915 if (!game.chats) game.chats = []; //live games don't have chat history
916 if (gtype == "corr") {
917 if (game.players[0].color == "b") {
918 // Adopt the same convention for live and corr games: [0] = white
919 [game.players[0], game.players[1]] = [
924 // NOTE: clocks in seconds, initime in milliseconds
925 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
926 game.clocks = [tc.mainTime, tc.mainTime];
927 const L = game.moves.length;
928 if (game.score == "*") {
929 // Set clocks + initime
930 game.initime = [0, 0];
932 const gameLastupdate = game.moves[L-1].played;
933 game.initime[L % 2] = gameLastupdate;
936 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
940 // Sort chat messages from newest to oldest
941 game.chats.sort((c1, c2) => {
942 return c2.added - c1.added;
944 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
945 // Did a chat message arrive after my last move?
947 if (L == 1 && myIdx == 0)
948 dtLastMove = game.moves[0].played;
951 // It's now white turn
952 dtLastMove = game.moves[L-1-(1-myIdx)].played;
955 dtLastMove = game.moves[L-1-myIdx].played;
958 if (dtLastMove < game.chats[0].added)
959 document.getElementById("chatBtn").classList.add("somethingnew");
961 // Now that we used idx and played, re-format moves as for live games
962 game.moves = game.moves.map(m => m.squares);
964 if (gtype == "live" && game.clocks[0] < 0) {
966 game.clocks = [tc.mainTime, tc.mainTime];
967 if (game.score == "*") {
968 game.initime[0] = Date.now();
970 // I play in this live game; corr games don't have clocks+initime
971 GameStorage.update(game.id, {
973 initime: game.initime
978 // TODO: merge next 2 "if" conditions
979 if (!!game.drawOffer) {
980 if (game.drawOffer == "t")
982 this.drawOffer = "threerep";
984 // Draw offered by any of the players:
985 if (myIdx < 0) this.drawOffer = "received";
987 // I play in this game:
989 (game.drawOffer == "w" && myIdx == 0) ||
990 (game.drawOffer == "b" && myIdx == 1)
992 this.drawOffer = "sent";
993 else this.drawOffer = "received";
997 if (!!game.rematchOffer) {
998 if (myIdx < 0) this.rematchOffer = "received";
1000 // I play in this game:
1002 (game.rematchOffer == "w" && myIdx == 0) ||
1003 (game.rematchOffer == "b" && myIdx == 1)
1005 this.rematchOffer = "sent";
1006 else this.rematchOffer = "received";
1009 this.repeat = {}; //reset: scan past moves' FEN:
1011 let vr_tmp = new V(game.fenStart);
1013 game.moves.forEach(m => {
1014 playMove(m, vr_tmp);
1015 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1016 this.repeat[fenIdx] = this.repeat[fenIdx]
1017 ? this.repeat[fenIdx] + 1
1020 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1021 this.game = Object.assign(
1022 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1025 increment: tc.increment,
1027 // opponent sid not strictly required (or available), but easier
1028 // at least oppsid or oppid is available anyway:
1029 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1030 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
1034 if (this.gameIsLoading)
1035 // Re-load game because we missed some moves:
1036 // artificially reset BaseGame (required if moves arrived in wrong order)
1037 this.$refs["basegame"].re_setVariables();
1040 this.gotMoveIdx = game.moves.length - 1;
1041 // If we arrive here after 'nextGame' action, the board might be hidden
1042 let boardDiv = document.querySelector(".game");
1043 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1044 boardDiv.style.visibility = "visible";
1046 this.re_setClocks();
1047 this.$nextTick(() => {
1048 this.game.rendered = true;
1049 // Did lastate arrive before game was rendered?
1050 if (this.lastate) this.processLastate();
1052 if (this.gameIsLoading) {
1053 this.gameIsLoading = false;
1054 if (this.gotMoveIdx >= game.moves.length)
1055 // Some moves arrived meanwhile...
1056 this.askGameAgain();
1058 if (!!callback) callback();
1061 afterRetrieval(game);
1064 if (this.gameRef.rid) {
1065 // Remote live game: forgetting about callback func... (TODO: design)
1066 this.send("askfullgame", { target: this.gameRef.rid });
1068 // Local or corr game on server.
1069 // NOTE: afterRetrieval() is never called if game not found
1070 const gid = this.gameRef.id;
1071 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
1072 // corr games identifiers are integers
1080 g.moves.forEach(m => {
1081 m.squares = JSON.parse(m.squares);
1090 GameStorage.get(this.gameRef.id, afterRetrieval);
1093 re_setClocks: function() {
1094 if (this.game.moves.length < 2 || this.game.score != "*") {
1095 // 1st move not completed yet, or game over: freeze time
1096 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1099 const currentTurn = this.vr.turn;
1100 const currentMovesCount = this.game.moves.length;
1101 const colorIdx = ["w", "b"].indexOf(currentTurn);
1103 this.game.clocks[colorIdx] -
1104 (Date.now() - this.game.initime[colorIdx]) / 1000;
1105 this.virtualClocks = [0, 1].map(i => {
1107 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
1108 return ppt(this.game.clocks[i] - removeTime).split(':');
1110 this.clockUpdate = setInterval(
1114 this.game.moves.length > currentMovesCount ||
1115 this.game.score != "*"
1117 clearInterval(this.clockUpdate);
1120 currentTurn == "w" ? "0-1" : "1-0",
1127 ppt(Math.max(0, --countdown)).split(':')
1133 // Update variables and storage after a move:
1134 processMove: function(move, data) {
1135 if (!data) data = {};
1136 const moveCol = this.vr.turn;
1137 const doProcessMove = () => {
1138 const colorIdx = ["w", "b"].indexOf(moveCol);
1139 const nextIdx = 1 - colorIdx;
1140 const origMovescount = this.game.moves.length;
1141 let addTime = 0; //for live games
1142 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1143 if (this.drawOffer == "received")
1145 this.drawOffer = "";
1146 if (this.game.type == "live" && origMovescount >= 2) {
1147 const elapsed = Date.now() - this.game.initime[colorIdx];
1148 // elapsed time is measured in milliseconds
1149 addTime = this.game.increment - elapsed / 1000;
1152 // Update current game object:
1153 playMove(move, this.vr);
1154 // The move is played: stop clock
1155 clearInterval(this.clockUpdate);
1157 // Received move, score has not been computed in BaseGame (!!noemit)
1158 const score = this.vr.getCurrentScore();
1159 if (score != "*") this.gameOver(score);
1161 // TODO: notifyTurn: "changeturn" message
1162 this.game.moves.push(move);
1163 this.game.fen = this.vr.getFen();
1164 if (this.game.type == "live") {
1165 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
1166 else this.game.clocks[colorIdx] += addTime;
1168 // 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 // Since corr games are stored at only one location, update should be
1193 // done only by one player for each move:
1195 !!this.game.mycolor &&
1196 !data.receiveMyMove &&
1197 (this.game.type == "live" || moveCol == this.game.mycolor)
1200 switch (this.drawOffer) {
1205 drawCode = this.game.mycolor;
1208 drawCode = V.GetOppCol(this.game.mycolor);
1211 if (this.game.type == "corr") {
1212 // corr: only move, fen and score
1213 this.updateCorrGame({
1216 squares: filtered_move,
1220 // Code "n" for "None" to force reset (otherwise it's ignored)
1221 drawOffer: drawCode || "n"
1225 const updateStorage = () => {
1226 GameStorage.update(this.gameRef.id, {
1228 move: filtered_move,
1229 moveIdx: origMovescount,
1230 clocks: this.game.clocks,
1231 initime: this.game.initime,
1235 // The active tab can update storage immediately
1236 if (!document.hidden) updateStorage();
1237 // Small random delay otherwise
1238 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1241 // Send move ("newmove" event) to people in the room (if our turn)
1242 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1244 move: filtered_move,
1245 index: origMovescount,
1246 // color is required to check if this is my move (if several tabs opened)
1248 cancelDrawOffer: this.drawOffer == ""
1250 if (this.game.type == "live")
1251 sendMove["clock"] = this.game.clocks[colorIdx];
1252 this.opponentGotMove = false;
1253 this.send("newmove", {data: sendMove});
1254 // If the opponent doesn't reply gotmove soon enough, re-send move:
1255 // Do this at most 2 times, because mpore would mean network issues,
1256 // opponent would then be expected to disconnect/reconnect.
1258 const currentUrl = document.location.href;
1259 this.retrySendmove = setInterval(
1263 this.opponentGotMove ||
1264 document.location.href != currentUrl //page change
1266 clearInterval(this.retrySendmove);
1269 const oppsid = this.getOppsid();
1271 // Opponent is disconnected: he'll ask last state
1272 clearInterval(this.retrySendmove);
1274 this.send("newmove", { data: sendMove, target: oppsid });
1282 // Not my move or I'm an observer: just start other player's clock
1283 this.re_setClocks();
1286 this.game.type == "corr" &&
1287 moveCol == this.game.mycolor &&
1290 let boardDiv = document.querySelector(".game");
1291 const afterSetScore = () => {
1293 if (this.st.settings.gotonext && this.nextIds.length > 0)
1294 this.showNextGame();
1296 // The board might have been hidden:
1297 if (boardDiv.style.visibility == "hidden")
1298 boardDiv.style.visibility = "visible";
1301 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1302 // We may play several moves in a row: in case of, remove listener:
1303 let elClone = el.cloneNode(true);
1304 el.parentNode.replaceChild(elClone, el);
1305 elClone.addEventListener(
1308 document.getElementById("modalConfirm").checked = false;
1309 if (!!data.score && data.score != "*")
1311 this.gameOver(data.score, null, afterSetScore);
1312 else afterSetScore();
1315 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1316 V.PlayOnBoard(this.vr.board, move);
1317 const position = this.vr.getBaseFen();
1318 V.UndoOnBoard(this.vr.board, move);
1319 if (["all","byrow"].includes(V.ShowMoves)) {
1320 this.curDiag = getDiagram({
1322 orientation: V.CanFlip ? this.game.mycolor : "w"
1324 document.querySelector("#confirmDiv > .card").style.width =
1325 boardDiv.offsetWidth + "px";
1327 // Incomplete information: just ask confirmation
1328 // Hide the board, because otherwise it could reveal infos
1329 boardDiv.style.visibility = "hidden";
1330 this.moveNotation = getFullNotation(move);
1332 document.getElementById("modalConfirm").checked = true;
1336 if (!!data.score && data.score != "*")
1337 this.gameOver(data.score, null, doProcessMove);
1338 else doProcessMove();
1341 cancelMove: function() {
1342 let boardDiv = document.querySelector(".game");
1343 if (boardDiv.style.visibility == "hidden")
1344 boardDiv.style.visibility = "visible";
1345 document.getElementById("modalConfirm").checked = false;
1346 this.$refs["basegame"].cancelLastMove();
1348 // In corr games, callback to change page only after score is set:
1349 gameOver: function(score, scoreMsg, callback) {
1350 this.game.score = score;
1351 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1352 this.game.scoreMsg = scoreMsg;
1353 this.$set(this.game, "scoreMsg", scoreMsg);
1354 const myIdx = this.game.players.findIndex(p => {
1355 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1358 // OK, I play in this game
1363 if (this.game.type == "live") {
1364 GameStorage.update(this.gameRef.id, scoreObj);
1365 if (!!callback) callback();
1367 else this.updateCorrGame(scoreObj, callback);
1368 // Notify the score to main Hall. TODO: only one player (currently double send)
1369 this.send("result", { gid: this.game.id, score: score });
1371 else if (!!callback) callback();
1377 <style lang="sass" scoped>
1383 background-color: lightgreen
1395 @media screen and (min-width: 768px)
1398 @media screen and (max-width: 767px)
1403 display: inline-block
1407 display: inline-block
1409 display: inline-flex
1413 @media screen and (max-width: 767px)
1416 @media screen and (max-width: 767px)
1419 @media screen and (min-width: 768px)
1431 background-color: #edda99
1433 display: inline-block
1442 display: inline-block
1455 animation: blink-animation 2s steps(3, start) infinite
1456 @keyframes blink-animation
1461 display: inline-block
1473 .draw-sent, .draw-sent:hover
1474 background-color: lightyellow
1476 .draw-received, .draw-received:hover
1477 background-color: lightgreen
1479 .draw-threerep, .draw-threerep:hover
1480 background-color: #e4d1fc
1482 .rematch-sent, .rematch-sent:hover
1483 background-color: lightyellow
1485 .rematch-received, .rematch-received:hover
1486 background-color: lightgreen
1489 background-color: #c5fefe
1502 background-color: lightgreen
1504 background-color: red