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
166 people: {}, //players + observers
167 onMygames: [], //opponents (or me) on "MyGames" page
168 lastate: undefined, //used if opponent send lastate before game is ready
169 repeat: {}, //detect position repetition
170 curDiag: "", //for corr moves confirmation
173 roomInitialized: false,
174 // If newmove has wrong index: ask fullgame again:
176 gameIsLoading: false,
177 // If asklastate got no reply, ask again:
179 gotMoveIdx: -1, //last move index received
180 // If newmove got no pingback, send again:
181 opponentGotMove: false,
183 // Incomplete info games: show move played
185 // Intervals from setInterval():
189 // Related to (killing of) self multi-connects:
195 $route: function(to, from) {
196 if (from.params["id"] != to.params["id"]) {
197 // Change everything:
198 this.cleanBeforeDestroy();
199 let boardDiv = document.querySelector(".game");
201 // In case of incomplete information variant:
202 boardDiv.style.visibility = "hidden";
206 this.gameRef.id = to.params["id"];
207 this.gameRef.rid = to.query["rid"];
208 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
213 // NOTE: some redundant code with Hall.vue (mostly related to people array)
214 created: function() {
217 mounted: function() {
218 document.addEventListener('visibilitychange', this.visibilityChange);
220 .getElementById("chatWrap")
221 .addEventListener("click", processModalClick);
222 if ("ontouchstart" in window) {
223 // Disable tooltips on smartphones:
224 document.getElementsByClassName("tooltip").forEach(elt => {
225 elt.classList.remove("tooltip");
229 beforeDestroy: function() {
230 document.removeEventListener('visibilitychange', this.visibilityChange);
231 this.cleanBeforeDestroy();
234 visibilityChange: function() {
235 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
237 document.visibilityState == "visible"
242 atCreation: function() {
243 // 0] (Re)Set variables
244 this.gameRef.id = this.$route.params["id"];
245 // rid = remote ID to find an observed live game,
246 // next = next corr games IDs to navigate faster
247 // (Both might be undefined)
248 this.gameRef.rid = this.$route.query["rid"];
249 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
250 // Always add myself to players' list
251 const my = this.st.user;
262 players: [{ name: "" }, { name: "" }],
266 let chatComp = this.$refs["chatcomp"];
267 if (!!chatComp) chatComp.chats = [];
268 this.virtualClocks = [[0,0], [0,0]];
271 this.rematchOffer = "";
273 this.lastate = undefined;
275 this.roomInitialized = false;
276 this.askGameTime = 0;
277 this.gameIsLoading = false;
278 this.gotLastate = false;
279 this.gotMoveIdx = -1;
280 this.opponentGotMove = false;
281 this.askLastate = null;
282 this.retrySendmove = null;
283 this.clockUpdate = null;
284 this.newConnect = {};
286 // 1] Initialize connection
287 this.connexionString =
294 // Discard potential "/?next=[...]" for page indication:
295 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
296 this.conn = new WebSocket(this.connexionString);
297 this.conn.onmessage = this.socketMessageListener;
298 this.conn.onclose = this.socketCloseListener;
299 // Socket init required before loading remote game:
300 const socketInit = callback => {
301 if (!!this.conn && this.conn.readyState == 1)
305 // Socket not ready yet (initial loading)
306 // NOTE: it's important to call callback without arguments,
307 // otherwise first arg is Websocket object and loadGame fails.
308 this.conn.onopen = () => callback();
310 if (!this.gameRef.rid)
311 // Game stored locally or on server
312 this.loadGame(null, () => socketInit(this.roomInit));
314 // Game stored remotely: need socket to retrieve it
315 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
316 // --> It will be given when receiving "fullgame" socket event.
317 socketInit(this.loadGame);
319 cleanBeforeDestroy: function() {
320 if (!!this.askLastate)
321 clearInterval(this.askLastate);
322 if (!!this.retrySendmove)
323 clearInterval(this.retrySendmove);
324 if (!!this.clockUpdate)
325 clearInterval(this.clockUpdate);
326 this.send("disconnect");
328 roomInit: function() {
329 if (!this.roomInitialized) {
330 // Notify the room only now that I connected, because
331 // messages might be lost otherwise (if game loading is slow)
332 this.send("connect");
333 this.send("pollclients");
334 // We may ask fullgame several times if some moves are lost,
335 // but room should be init only once:
336 this.roomInitialized = true;
339 send: function(code, obj) {
341 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
343 isConnected: function(index) {
344 const player = this.game.players[index];
345 // Is it me ? In this case no need to bother with focus
346 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
347 // Still have to check for name (because of potential multi-accounts
348 // on same browser, although this should be rare...)
349 return (!this.st.user.name || this.st.user.name == player.name);
350 // Try to find a match in people:
354 Object.keys(this.people).some(sid =>
355 sid == player.sid && this.people[sid].focus)
360 Object.values(this.people).some(p =>
361 p.id == player.uid && p.focus)
365 getOppsid: function() {
366 let oppsid = this.game.oppsid;
368 oppsid = Object.keys(this.people).find(
369 sid => this.people[sid].id == this.game.oppid
372 // oppsid is useful only if opponent is online:
373 if (!!oppsid && !!this.people[oppsid]) return oppsid;
376 resetChatColor: function() {
377 // TODO: this is called twice, once on opening an once on closing
378 document.getElementById("chatBtn").classList.remove("somethingnew");
380 processChat: function(chat) {
381 this.send("newchat", { data: chat });
382 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
383 if (this.game.type == "corr" && this.st.user.id > 0)
384 this.updateCorrGame({ chat: chat });
386 clearChat: function() {
387 // Nothing more to do if game is live (chats not recorded)
388 if (this.game.type == "corr") {
389 if (!!this.game.mycolor) {
393 { data: { gid: this.game.id } }
396 this.$set(this.game, "chats", []);
399 // Notify turn after a new move (to opponent and me on MyGames page)
400 notifyTurn: function(sid) {
401 const player = this.people[sid];
402 const colorIdx = this.game.players.findIndex(
403 p => p.sid == sid || p.uid == player.id);
404 const color = ["w","b"][colorIdx];
405 const movesCount = this.game.moves.length;
407 (color == "w" && movesCount % 2 == 0) ||
408 (color == "b" && movesCount % 2 == 1);
409 this.send("turnchange", { target: sid, yourTurn: yourTurn });
411 showNextGame: function() {
412 // Did I play in current game? If not, add it to nextIds list
413 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
414 this.nextIds.unshift(this.game.id);
415 const nextGid = this.nextIds.pop();
417 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
419 askGameAgain: function() {
420 this.gameIsLoading = true;
421 const currentUrl = document.location.href;
422 const doAskGame = () => {
423 if (document.location.href != currentUrl) return; //page change
424 if (!this.gameRef.rid)
425 // This is my game: just reload.
428 // Just ask fullgame again (once!), this is much simpler.
429 // If this fails, the user could just reload page :/
430 this.send("askfullgame", { target: this.gameRef.rid });
432 // Delay of at least 2s between two game requests
433 const now = Date.now();
434 const delay = Math.max(2000 - (now - this.askGameTime), 0);
435 this.askGameTime = now;
436 setTimeout(doAskGame, delay);
438 socketMessageListener: function(msg) {
439 if (!this.conn) return;
440 const data = JSON.parse(msg.data);
443 data.sockIds.forEach(sid => {
444 if (sid != this.st.user.sid) {
445 this.people[sid] = { focus: true };
446 this.send("askidentity", { target: sid });
451 if (!this.people[data.from]) {
452 this.people[data.from] = { focus: true };
453 this.newConnect[data.from] = true; //for self multi-connects tests
454 this.send("askidentity", { target: data.from });
458 this.$delete(this.people, data.from);
461 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
462 // Either me (another tab) or opponent
463 const sid = data.from;
464 if (!this.onMygames.some(s => s == sid))
466 this.onMygames.push(sid);
467 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
470 if (!this.people[sid])
471 this.send("askidentity", { target: sid });
474 ArrayFun.remove(this.onMygames, sid => sid == data.from);
477 let player = this.people[data.from];
480 this.$forceUpdate(); //TODO: shouldn't be required
485 let player = this.people[data.from];
487 player.focus = false;
488 this.$forceUpdate(); //TODO: shouldn't be required
493 // I logged in elsewhere:
495 alert(this.st.tr["New connexion detected: tab now offline"]);
497 case "askidentity": {
498 // Request for identification
500 // Decompose to avoid revealing email
501 name: this.st.user.name,
502 sid: this.st.user.sid,
505 this.send("identity", { data: me, target: data.from });
509 const user = data.data;
510 let player = this.people[user.sid];
511 // player.focus is already set
512 player.name = user.name;
514 this.$forceUpdate(); //TODO: shouldn't be required
515 // If I multi-connect, kill current connexion if no mark (I'm older)
516 if (this.newConnect[user.sid]) {
519 user.id == this.st.user.id &&
520 user.sid != this.st.user.sid &&
521 !this.killed[this.st.user.sid]
523 this.send("killme", { sid: this.st.user.sid });
524 this.killed[this.st.user.sid] = true;
526 delete this.newConnect[user.sid];
528 if (!this.killed[this.st.user.sid]) {
529 // Ask potentially missed last state, if opponent and I play
531 !!this.game.mycolor &&
532 this.game.type == "live" &&
533 this.game.score == "*" &&
534 this.game.players.some(p => p.sid == user.sid)
536 this.send("asklastate", { target: user.sid });
538 this.askLastate = setInterval(
540 // Ask at most 3 times:
541 // if no reply after that there should be a network issue.
545 !!this.people[user.sid]
547 this.send("asklastate", { target: user.sid });
550 clearInterval(this.askLastate);
560 // Send current (live) game if not asked by any of the players
562 this.game.type == "live" &&
563 this.game.players.every(p => p.sid != data.from[0])
568 players: this.game.players,
570 cadence: this.game.cadence,
571 score: this.game.score,
572 rid: this.st.user.sid //useful in Hall if I'm an observer
574 this.send("game", { data: myGame, target: data.from });
578 const gameToSend = Object.keys(this.game)
581 "id","fen","players","vid","cadence","fenStart","vname",
582 "moves","clocks","initime","score","drawOffer","rematchOffer"
586 obj[k] = this.game[k];
591 this.send("fullgame", { data: gameToSend, target: data.from });
594 // Callback "roomInit" to poll clients only after game is loaded
595 this.loadGame(data.data, this.roomInit);
598 // Sending informative last state if I played a move or score != "*"
600 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
601 this.game.score != "*" ||
602 this.drawOffer == "sent" ||
603 this.rematchOffer == "sent"
605 // Send our "last state" informations to opponent
606 const L = this.game.moves.length;
607 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
609 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
610 clock: this.game.clocks[myIdx],
611 // Since we played a move (or abort or resign),
612 // only drawOffer=="sent" is possible
613 drawSent: this.drawOffer == "sent",
614 rematchSent: this.rematchOffer == "sent",
615 score: this.game.score,
616 score: this.game.scoreMsg,
618 initime: this.game.initime[1 - myIdx] //relevant only if I played
620 this.send("lastate", { data: myLastate, target: data.from });
622 this.send("lastate", { data: {nothing: true}, target: data.from });
626 // Got opponent infos about last move
627 this.gotLastate = true;
628 if (!data.data.nothing) {
629 this.lastate = data.data;
630 if (this.game.rendered)
631 // Game is rendered (Board component)
632 this.processLastate();
633 // Else: will be processed when game is ready
638 const movePlus = data.data;
639 const movesCount = this.game.moves.length;
640 if (movePlus.index > movesCount) {
641 // This can only happen if I'm an observer and missed a move.
642 if (this.gotMoveIdx < movePlus.index)
643 this.gotMoveIdx = movePlus.index;
644 if (!this.gameIsLoading) this.askGameAgain();
648 movePlus.index < movesCount ||
649 this.gotMoveIdx >= movePlus.index
651 // Opponent re-send but we already have the move:
652 // (maybe he didn't receive our pingback...)
653 this.send("gotmove", {data: movePlus.index, target: data.from});
655 this.gotMoveIdx = movePlus.index;
656 const receiveMyMove = (movePlus.color == this.game.mycolor);
657 if (!receiveMyMove && !!this.game.mycolor)
658 // Notify opponent that I got the move:
659 this.send("gotmove", {data: movePlus.index, target: data.from});
660 if (movePlus.cancelDrawOffer) {
661 // Opponent refuses draw
663 // NOTE for corr games: drawOffer reset by player in turn
665 this.game.type == "live" &&
666 !!this.game.mycolor &&
669 GameStorage.update(this.gameRef.id, { drawOffer: "" });
672 this.$refs["basegame"].play(movePlus.move, "received", null, true);
676 clock: movePlus.clock,
677 receiveMyMove: receiveMyMove
685 this.opponentGotMove = true;
686 // Now his clock starts running:
687 const oppIdx = ['w','b'].indexOf(this.vr.turn);
688 this.game.initime[oppIdx] = Date.now();
693 const score = data.side == "b" ? "1-0" : "0-1";
694 const side = data.side == "w" ? "White" : "Black";
695 this.gameOver(score, side + " surrender");
698 this.gameOver("?", "Stop");
701 this.gameOver("1/2", data.data);
704 // NOTE: observers don't know who offered draw
705 this.drawOffer = "received";
708 // NOTE: observers don't know who offered rematch
709 this.rematchOffer = data.data ? "received" : "";
712 // A game started, redirect if I'm playing in
713 const gameInfo = data.data;
715 gameInfo.players.some(p =>
716 p.sid == this.st.user.sid || p.uid == this.st.user.id)
718 this.$router.push("/game/" + gameInfo.id);
721 if (gameInfo.cadence.indexOf('d') === -1) {
723 // Select sid of any of the online players:
725 gameInfo.players.forEach(p => {
726 if (!!this.people[p.sid]) onlineSid.push(p.sid);
728 urlRid += onlineSid[Math.floor(Math.random() * onlineSid.length)];
731 this.st.tr["Rematch in progress:"] +
732 " <a href='#/game/" +
733 gameInfo.id + urlRid +
736 gameInfo.id + urlRid +
738 document.getElementById("modalInfo").checked = true;
743 this.newChat = data.data;
744 if (!document.getElementById("modalChat").checked)
745 document.getElementById("chatBtn").classList.add("somethingnew");
749 socketCloseListener: function() {
750 this.conn = new WebSocket(this.connexionString);
751 this.conn.addEventListener("message", this.socketMessageListener);
752 this.conn.addEventListener("close", this.socketCloseListener);
754 updateCorrGame: function(obj, callback) {
760 gid: this.gameRef.id,
764 if (!!callback) callback();
769 // lastate was received, but maybe game wasn't ready yet:
770 processLastate: function() {
771 const data = this.lastate;
772 this.lastate = undefined; //security...
773 const L = this.game.moves.length;
774 if (data.movesCount > L) {
775 // Just got last move from him
776 this.$refs["basegame"].play(data.lastMove, "received", null, true);
777 this.processMove(data.lastMove, { clock: data.clock });
779 if (data.drawSent) this.drawOffer = "received";
780 if (data.rematchSent) this.rematchOffer = "received";
781 if (data.score != "*") {
783 if (this.game.score == "*")
784 this.gameOver(data.score, data.scoreMsg);
787 clickDraw: function() {
788 if (!this.game.mycolor) return; //I'm just spectator
789 if (["received", "threerep"].includes(this.drawOffer)) {
790 if (!confirm(this.st.tr["Accept draw?"])) return;
792 this.drawOffer == "received"
794 : "Three repetitions";
795 this.send("draw", { data: message });
796 this.gameOver("1/2", message);
797 } else if (this.drawOffer == "") {
798 // No effect if drawOffer == "sent"
799 if (this.game.mycolor != this.vr.turn) {
800 alert(this.st.tr["Draw offer only in your turn"]);
803 if (!confirm(this.st.tr["Offer draw?"])) return;
804 this.drawOffer = "sent";
805 this.send("drawoffer");
806 if (this.game.type == "live") {
809 { drawOffer: this.game.mycolor }
811 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
814 clickRematch: function() {
815 if (!this.game.mycolor) return; //I'm just spectator
816 if (this.rematchOffer == "received") {
819 id: getRandString(), //ignored if corr
820 fen: V.GenRandInitFen(this.game.randomness),
821 players: this.game.players.reverse(),
823 cadence: this.game.cadence
825 let oppsid = this.getOppsid(); //may be null
826 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
827 if (this.game.type == "live") {
828 const game = Object.assign(
832 // (other) Game infos: constant
833 fenStart: gameInfo.fen,
834 vname: this.game.vname,
836 // Game state (including FEN): will be updated
838 clocks: [-1, -1], //-1 = unstarted
839 initime: [0, 0], //initialized later
843 GameStorage.add(game, (err) => {
844 // No error expected.
846 if (this.st.settings.sound)
847 new Audio("/sounds/newgame.flac").play().catch(() => {});
848 this.$router.push("/game/" + gameInfo.id);
858 // cid is useful to delete the challenge:
859 data: { gameInfo: gameInfo },
860 success: (response) => {
861 gameInfo.id = response.gameId;
862 this.$router.push("/game/" + response.gameId);
867 } else if (this.rematchOffer == "") {
868 this.rematchOffer = "sent";
869 this.send("rematchoffer", { data: true });
870 if (this.game.type == "live") {
873 { rematchOffer: this.game.mycolor }
875 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
876 } else if (this.rematchOffer == "sent") {
877 // Toggle rematch offer (on --> off)
878 this.rematchOffer = "";
879 this.send("rematchoffer", { data: false });
880 if (this.game.type == "live") {
885 } else this.updateCorrGame({ rematchOffer: 'n' });
888 abortGame: function() {
889 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
890 this.gameOver("?", "Stop");
894 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
896 this.send("resign", { data: this.game.mycolor });
897 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
898 const side = this.game.mycolor == "w" ? "White" : "Black";
899 this.gameOver(score, side + " surrender");
901 // 3 cases for loading a game:
902 // - from indexedDB (running or completed live game I play)
903 // - from server (one correspondance game I play[ed] or not)
904 // - from remote peer (one live game I don't play, finished or not)
905 loadGame: function(game, callback) {
906 const afterRetrieval = async game => {
907 const vModule = await import("@/variants/" + game.vname + ".js");
908 window.V = vModule.VariantRules;
909 this.vr = new V(game.fen);
910 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
911 const tc = extractTime(game.cadence);
912 const myIdx = game.players.findIndex(p => {
913 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
915 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
916 if (!game.chats) game.chats = []; //live games don't have chat history
917 if (gtype == "corr") {
918 if (game.players[0].color == "b") {
919 // Adopt the same convention for live and corr games: [0] = white
920 [game.players[0], game.players[1]] = [
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 = [0, 0];
933 const gameLastupdate = game.moves[L-1].played;
934 game.initime[L % 2] = gameLastupdate;
937 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
941 // Sort chat messages from newest to oldest
942 game.chats.sort((c1, c2) => {
943 return c2.added - c1.added;
945 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
946 // Did a chat message arrive after my last move?
948 if (L == 1 && myIdx == 0)
949 dtLastMove = game.moves[0].played;
952 // It's now white turn
953 dtLastMove = game.moves[L-1-(1-myIdx)].played;
956 dtLastMove = game.moves[L-1-myIdx].played;
959 if (dtLastMove < game.chats[0].added)
960 document.getElementById("chatBtn").classList.add("somethingnew");
962 // Now that we used idx and played, re-format moves as for live games
963 game.moves = game.moves.map(m => m.squares);
965 if (gtype == "live" && game.clocks[0] < 0) {
967 game.clocks = [tc.mainTime, tc.mainTime];
968 if (game.score == "*") {
969 game.initime[0] = Date.now();
971 // I play in this live game; corr games don't have clocks+initime
972 GameStorage.update(game.id, {
974 initime: game.initime
979 // TODO: merge next 2 "if" conditions
980 if (!!game.drawOffer) {
981 if (game.drawOffer == "t")
983 this.drawOffer = "threerep";
985 // Draw offered by any of the players:
986 if (myIdx < 0) this.drawOffer = "received";
988 // I play in this game:
990 (game.drawOffer == "w" && myIdx == 0) ||
991 (game.drawOffer == "b" && myIdx == 1)
993 this.drawOffer = "sent";
994 else this.drawOffer = "received";
998 if (!!game.rematchOffer) {
999 if (myIdx < 0) this.rematchOffer = "received";
1001 // I play in this game:
1003 (game.rematchOffer == "w" && myIdx == 0) ||
1004 (game.rematchOffer == "b" && myIdx == 1)
1006 this.rematchOffer = "sent";
1007 else this.rematchOffer = "received";
1010 this.repeat = {}; //reset: scan past moves' FEN:
1012 let vr_tmp = new V(game.fenStart);
1014 game.moves.forEach(m => {
1015 playMove(m, vr_tmp);
1016 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1017 this.repeat[fenIdx] = this.repeat[fenIdx]
1018 ? this.repeat[fenIdx] + 1
1021 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1022 this.game = Object.assign(
1023 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1026 increment: tc.increment,
1028 // opponent sid not strictly required (or available), but easier
1029 // at least oppsid or oppid is available anyway:
1030 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1031 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
1035 if (this.gameIsLoading)
1036 // Re-load game because we missed some moves:
1037 // artificially reset BaseGame (required if moves arrived in wrong order)
1038 this.$refs["basegame"].re_setVariables();
1041 this.gotMoveIdx = game.moves.length - 1;
1042 // If we arrive here after 'nextGame' action, the board might be hidden
1043 let boardDiv = document.querySelector(".game");
1044 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1045 boardDiv.style.visibility = "visible";
1047 this.re_setClocks();
1048 this.$nextTick(() => {
1049 this.game.rendered = true;
1050 // Did lastate arrive before game was rendered?
1051 if (this.lastate) this.processLastate();
1053 if (this.gameIsLoading) {
1054 this.gameIsLoading = false;
1055 if (this.gotMoveIdx >= game.moves.length)
1056 // Some moves arrived meanwhile...
1057 this.askGameAgain();
1059 if (!!callback) callback();
1062 afterRetrieval(game);
1065 if (this.gameRef.rid) {
1066 // Remote live game: forgetting about callback func... (TODO: design)
1067 this.send("askfullgame", { target: this.gameRef.rid });
1069 // Local or corr game on server.
1070 // NOTE: afterRetrieval() is never called if game not found
1071 const gid = this.gameRef.id;
1072 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
1073 // corr games identifiers are integers
1081 g.moves.forEach(m => {
1082 m.squares = JSON.parse(m.squares);
1091 GameStorage.get(this.gameRef.id, afterRetrieval);
1094 re_setClocks: function() {
1095 if (this.game.moves.length < 2 || this.game.score != "*") {
1096 // 1st move not completed yet, or game over: freeze time
1097 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1100 const currentTurn = this.vr.turn;
1101 const currentMovesCount = this.game.moves.length;
1102 const colorIdx = ["w", "b"].indexOf(currentTurn);
1104 this.game.clocks[colorIdx] -
1105 (Date.now() - this.game.initime[colorIdx]) / 1000;
1106 this.virtualClocks = [0, 1].map(i => {
1108 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
1109 return ppt(this.game.clocks[i] - removeTime).split(':');
1111 this.clockUpdate = setInterval(
1115 this.game.moves.length > currentMovesCount ||
1116 this.game.score != "*"
1118 clearInterval(this.clockUpdate);
1121 currentTurn == "w" ? "0-1" : "1-0",
1128 ppt(Math.max(0, --countdown)).split(':')
1134 // Update variables and storage after a move:
1135 processMove: function(move, data) {
1136 if (!data) data = {};
1137 const moveCol = this.vr.turn;
1138 const doProcessMove = () => {
1139 const colorIdx = ["w", "b"].indexOf(moveCol);
1140 const nextIdx = 1 - colorIdx;
1141 const origMovescount = this.game.moves.length;
1142 let addTime = 0; //for live games
1143 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1144 if (this.drawOffer == "received")
1146 this.drawOffer = "";
1147 if (this.game.type == "live" && origMovescount >= 2) {
1148 const elapsed = Date.now() - this.game.initime[colorIdx];
1149 // elapsed time is measured in milliseconds
1150 addTime = this.game.increment - elapsed / 1000;
1153 // Update current game object:
1154 playMove(move, this.vr);
1155 // The move is played: stop clock
1156 clearInterval(this.clockUpdate);
1158 // Received move, score has not been computed in BaseGame (!!noemit)
1159 const score = this.vr.getCurrentScore();
1160 if (score != "*") this.gameOver(score);
1162 // TODO: notifyTurn: "changeturn" message
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:
1171 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1173 // NOTE: opponent's initime is reset after "gotmove" is received
1175 !this.game.mycolor ||
1176 moveCol != this.game.mycolor ||
1177 !!data.receiveMyMove
1179 this.game.initime[nextIdx] = Date.now();
1181 // If repetition detected, consider that a draw offer was received:
1182 const fenObj = this.vr.getFenForRepeat();
1183 this.repeat[fenObj] =
1184 !!this.repeat[fenObj]
1185 ? this.repeat[fenObj] + 1
1187 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1188 else if (this.drawOffer == "threerep") this.drawOffer = "";
1189 if (!!this.game.mycolor && !data.receiveMyMove) {
1190 // NOTE: 'var' to see that variable outside this block
1191 var filtered_move = getFilteredMove(move);
1193 // Since corr games are stored at only one location, update should be
1194 // done only by one player for each move:
1196 !!this.game.mycolor &&
1197 !data.receiveMyMove &&
1198 (this.game.type == "live" || moveCol == this.game.mycolor)
1201 switch (this.drawOffer) {
1206 drawCode = this.game.mycolor;
1209 drawCode = V.GetOppCol(this.game.mycolor);
1212 if (this.game.type == "corr") {
1213 // corr: only move, fen and score
1214 this.updateCorrGame({
1217 squares: filtered_move,
1221 // Code "n" for "None" to force reset (otherwise it's ignored)
1222 drawOffer: drawCode || "n"
1226 const updateStorage = () => {
1227 GameStorage.update(this.gameRef.id, {
1229 move: filtered_move,
1230 moveIdx: origMovescount,
1231 clocks: this.game.clocks,
1232 initime: this.game.initime,
1236 // The active tab can update storage immediately
1237 if (!document.hidden) updateStorage();
1238 // Small random delay otherwise
1239 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1242 // Send move ("newmove" event) to people in the room (if our turn)
1243 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1245 move: filtered_move,
1246 index: origMovescount,
1247 // color is required to check if this is my move (if several tabs opened)
1249 cancelDrawOffer: this.drawOffer == ""
1251 if (this.game.type == "live")
1252 sendMove["clock"] = this.game.clocks[colorIdx];
1253 this.opponentGotMove = false;
1254 this.send("newmove", {data: sendMove});
1255 // If the opponent doesn't reply gotmove soon enough, re-send move:
1256 // Do this at most 2 times, because mpore would mean network issues,
1257 // opponent would then be expected to disconnect/reconnect.
1259 const currentUrl = document.location.href;
1260 this.retrySendmove = setInterval(
1264 this.opponentGotMove ||
1265 document.location.href != currentUrl //page change
1267 clearInterval(this.retrySendmove);
1270 const oppsid = this.getOppsid();
1272 // Opponent is disconnected: he'll ask last state
1273 clearInterval(this.retrySendmove);
1275 this.send("newmove", { data: sendMove, target: oppsid });
1283 // Not my move or I'm an observer: just start other player's clock
1284 this.re_setClocks();
1287 this.game.type == "corr" &&
1288 moveCol == this.game.mycolor &&
1291 let boardDiv = document.querySelector(".game");
1292 const afterSetScore = () => {
1294 if (this.st.settings.gotonext && this.nextIds.length > 0)
1295 this.showNextGame();
1297 // The board might have been hidden:
1298 if (boardDiv.style.visibility == "hidden")
1299 boardDiv.style.visibility = "visible";
1302 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1303 // We may play several moves in a row: in case of, remove listener:
1304 let elClone = el.cloneNode(true);
1305 el.parentNode.replaceChild(elClone, el);
1306 elClone.addEventListener(
1309 document.getElementById("modalConfirm").checked = false;
1310 if (!!data.score && data.score != "*")
1312 this.gameOver(data.score, null, afterSetScore);
1313 else afterSetScore();
1316 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1317 V.PlayOnBoard(this.vr.board, move);
1318 const position = this.vr.getBaseFen();
1319 V.UndoOnBoard(this.vr.board, move);
1320 if (["all","byrow"].includes(V.ShowMoves)) {
1321 this.curDiag = getDiagram({
1323 orientation: V.CanFlip ? this.game.mycolor : "w"
1325 document.querySelector("#confirmDiv > .card").style.width =
1326 boardDiv.offsetWidth + "px";
1328 // Incomplete information: just ask confirmation
1329 // Hide the board, because otherwise it could reveal infos
1330 boardDiv.style.visibility = "hidden";
1331 this.moveNotation = getFullNotation(move);
1333 document.getElementById("modalConfirm").checked = true;
1337 if (!!data.score && data.score != "*")
1338 this.gameOver(data.score, null, doProcessMove);
1339 else doProcessMove();
1342 cancelMove: function() {
1343 let boardDiv = document.querySelector(".game");
1344 if (boardDiv.style.visibility == "hidden")
1345 boardDiv.style.visibility = "visible";
1346 document.getElementById("modalConfirm").checked = false;
1347 this.$refs["basegame"].cancelLastMove();
1349 // In corr games, callback to change page only after score is set:
1350 gameOver: function(score, scoreMsg, callback) {
1351 this.game.score = score;
1352 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1353 this.game.scoreMsg = scoreMsg;
1354 this.$set(this.game, "scoreMsg", scoreMsg);
1355 const myIdx = this.game.players.findIndex(p => {
1356 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1359 // OK, I play in this game
1364 if (this.game.type == "live") {
1365 GameStorage.update(this.gameRef.id, scoreObj);
1366 if (!!callback) callback();
1368 else this.updateCorrGame(scoreObj, callback);
1369 // Notify the score to main Hall. TODO: only one player (currently double send)
1370 this.send("result", { gid: this.game.id, score: score });
1372 else if (!!callback) callback();
1378 <style lang="sass" scoped>
1384 background-color: lightgreen
1396 @media screen and (min-width: 768px)
1399 @media screen and (max-width: 767px)
1404 display: inline-block
1408 display: inline-block
1410 display: inline-flex
1414 @media screen and (max-width: 767px)
1417 @media screen and (max-width: 767px)
1420 @media screen and (min-width: 768px)
1432 background-color: #edda99
1434 display: inline-block
1443 display: inline-block
1456 animation: blink-animation 2s steps(3, start) infinite
1457 @keyframes blink-animation
1462 display: inline-block
1474 .draw-sent, .draw-sent:hover
1475 background-color: lightyellow
1477 .draw-received, .draw-received:hover
1478 background-color: lightgreen
1480 .draw-threerep, .draw-threerep:hover
1481 background-color: #e4d1fc
1483 .rematch-sent, .rematch-sent:hover
1484 background-color: lightyellow
1486 .rematch-received, .rematch-received:hover
1487 background-color: lightgreen
1490 background-color: #c5fefe
1503 background-color: lightgreen
1505 background-color: red