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(
17 @click="resetChatColor()"
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"
42 @chatcleared="clearChat"
44 input#modalConfirm.modal(type="checkbox")
45 div#confirmDiv(role="dialog")
48 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
52 span {{ st.tr["Move played:"] + " " }}
53 span.bold {{ moveNotation }}
55 span {{ st.tr["Are you sure?"] }}
56 .button-group#buttonsConfirm
57 // onClick for acceptBtn: set dynamically
59 span {{ st.tr["Validate"] }}
60 button.refuseBtn(@click="cancelMove()")
61 span {{ st.tr["Cancel"] }}
63 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
64 span.variant-cadence {{ game.cadence }}
65 span.variant-name {{ game.vname }}
67 v-if="nextIds.length > 0"
68 @click="showNextGame()"
70 | {{ st.tr["Next_g"] }}
71 button#chatBtn.tooltip(
72 onClick="window.doClick('modalChat')"
75 img(src="/images/icons/chat.svg")
76 #actions(v-if="game.score=='*'")
79 :class="{['draw-' + drawOffer]: true}"
80 :aria-label="st.tr['Draw']"
82 img(src="/images/icons/draw.svg")
86 :aria-label="st.tr['Abort']"
88 img(src="/images/icons/abort.svg")
92 :aria-label="st.tr['Resign']"
94 img(src="/images/icons/resign.svg")
97 @click="clickRematch()"
98 :class="{['rematch-' + rematchOffer]: true}"
99 :aria-label="st.tr['Rematch']"
101 img(src="/images/icons/rematch.svg")
104 span.name(:class="{connected: isConnected(0)}")
105 | {{ game.players[0].name || "@nonymous" }}
107 v-if="game.score=='*'"
108 :class="{yourturn: !!vr && vr.turn == 'w'}"
110 span.time-left {{ virtualClocks[0][0] }}
111 span.time-separator(v-if="!!virtualClocks[0][1]") :
112 span.time-right(v-if="!!virtualClocks[0][1]")
113 | {{ virtualClocks[0][1] }}
115 span.name(:class="{connected: isConnected(1)}")
116 | {{ game.players[1].name || "@nonymous" }}
118 v-if="game.score=='*'"
119 :class="{yourturn: !!vr && vr.turn == 'b'}"
121 span.time-left {{ virtualClocks[1][0] }}
122 span.time-separator(v-if="!!virtualClocks[1][1]") :
123 span.time-right(v-if="!!virtualClocks[1][1]")
124 | {{ virtualClocks[1][1] }}
128 @newmove="processMove"
133 import BaseGame from "@/components/BaseGame.vue";
134 import Chat from "@/components/Chat.vue";
135 import { store } from "@/store";
136 import { GameStorage } from "@/utils/gameStorage";
137 import { ppt } from "@/utils/datetime";
138 import { ajax } from "@/utils/ajax";
139 import { extractTime } from "@/utils/timeControl";
140 import { getRandString } from "@/utils/alea";
141 import { getScoreMessage } from "@/utils/scoring";
142 import { getFullNotation } from "@/utils/notation";
143 import { getDiagram } from "@/utils/printDiagram";
144 import { processModalClick } from "@/utils/modalClick";
145 import { playMove, getFilteredMove } from "@/utils/playUndo";
146 import { ArrayFun } from "@/utils/array";
147 import params from "@/parameters";
158 // rid = remote (socket) ID
163 game: {}, //passed to BaseGame
164 // virtualClocks will be initialized from true game.clocks
166 vr: null, //"variant rules" object initialized from FEN
171 people: {}, //players + observers
172 lastate: undefined, //used if opponent send lastate before game is ready
173 repeat: {}, //detect position repetition
174 curDiag: "", //for corr moves confirmation
177 roomInitialized: false,
178 // If newmove has wrong index: ask fullgame again:
180 gameIsLoading: false,
181 // If asklastate got no reply, ask again:
183 gotMoveIdx: -1, //last move index received
184 // If newmove got no pingback, send again:
185 opponentGotMove: false,
187 // Incomplete info games: show move played
189 // Intervals from setInterval():
193 // Related to (killing of) self multi-connects:
199 $route: function(to, from) {
200 if (from.params["id"] != to.params["id"]) {
201 // Change everything:
202 this.cleanBeforeDestroy();
203 let boardDiv = document.querySelector(".game");
205 // In case of incomplete information variant:
206 boardDiv.style.visibility = "hidden";
210 this.gameRef.id = to.params["id"];
211 this.gameRef.rid = to.query["rid"];
212 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
217 // NOTE: some redundant code with Hall.vue (mostly related to people array)
218 created: function() {
221 mounted: function() {
222 document.addEventListener('visibilitychange', this.visibilityChange);
223 ["chatWrap", "infoDiv"].forEach(eltName => {
224 document.getElementById(eltName)
225 .addEventListener("click", processModalClick);
227 if ("ontouchstart" in window) {
228 // Disable tooltips on smartphones:
229 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
230 elt.classList.remove("tooltip");
234 beforeDestroy: function() {
235 document.removeEventListener('visibilitychange', this.visibilityChange);
236 this.cleanBeforeDestroy();
239 visibilityChange: function() {
240 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
242 document.visibilityState == "visible"
247 atCreation: function() {
248 // 0] (Re)Set variables
249 this.gameRef.id = this.$route.params["id"];
250 // rid = remote ID to find an observed live game,
251 // next = next corr games IDs to navigate faster
252 // (Both might be undefined)
253 this.gameRef.rid = this.$route.query["rid"];
254 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
255 // Always add myself to players' list
256 const my = this.st.user;
267 players: [{ name: "" }, { name: "" }],
271 let chatComp = this.$refs["chatcomp"];
272 if (!!chatComp) chatComp.chats = [];
273 this.virtualClocks = [[0,0], [0,0]];
276 this.lastateAsked = false;
277 this.rematchOffer = "";
278 this.lastate = undefined;
280 this.roomInitialized = false;
281 this.askGameTime = 0;
282 this.gameIsLoading = false;
283 this.gotLastate = false;
284 this.gotMoveIdx = -1;
285 this.opponentGotMove = false;
286 this.askLastate = null;
287 this.retrySendmove = null;
288 this.clockUpdate = null;
289 this.newConnect = {};
291 // 1] Initialize connection
292 this.connexionString =
301 // Discard potential "/?next=[...]" for page indication:
302 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
303 this.conn = new WebSocket(this.connexionString);
304 this.conn.onmessage = this.socketMessageListener;
305 this.conn.onclose = this.socketCloseListener;
306 // Socket init required before loading remote game:
307 const socketInit = callback => {
308 if (!!this.conn && this.conn.readyState == 1)
312 // Socket not ready yet (initial loading)
313 // NOTE: it's important to call callback without arguments,
314 // otherwise first arg is Websocket object and loadGame fails.
315 this.conn.onopen = () => callback();
317 if (!this.gameRef.rid)
318 // Game stored locally or on server
319 this.loadGame(null, () => socketInit(this.roomInit));
321 // Game stored remotely: need socket to retrieve it
322 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
323 // --> It will be given when receiving "fullgame" socket event.
324 socketInit(this.loadGame);
326 cleanBeforeDestroy: function() {
327 if (!!this.askLastate)
328 clearInterval(this.askLastate);
329 if (!!this.retrySendmove)
330 clearInterval(this.retrySendmove);
331 if (!!this.clockUpdate)
332 clearInterval(this.clockUpdate);
333 this.send("disconnect");
335 roomInit: function() {
336 if (!this.roomInitialized) {
337 // Notify the room only now that I connected, because
338 // messages might be lost otherwise (if game loading is slow)
339 this.send("connect");
340 this.send("pollclients");
341 // We may ask fullgame several times if some moves are lost,
342 // but room should be init only once:
343 this.roomInitialized = true;
346 send: function(code, obj) {
348 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
350 isConnected: function(index) {
351 const player = this.game.players[index];
352 // Is it me ? In this case no need to bother with focus
353 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
354 // Still have to check for name (because of potential multi-accounts
355 // on same browser, although this should be rare...)
356 return (!this.st.user.name || this.st.user.name == player.name);
357 // Try to find a match in people:
361 Object.keys(this.people).some(sid =>
362 sid == player.sid && this.people[sid].focus)
367 Object.values(this.people).some(p =>
368 p.id == player.id && p.focus)
372 getOppsid: function() {
373 let oppsid = this.game.oppsid;
375 oppsid = Object.keys(this.people).find(
376 sid => this.people[sid].id == this.game.oppid
379 // oppsid is useful only if opponent is online:
380 if (!!oppsid && !!this.people[oppsid]) return oppsid;
383 resetChatColor: function() {
384 // TODO: this is called twice, once on opening an once on closing
385 document.getElementById("chatBtn").classList.remove("somethingnew");
387 processChat: function(chat) {
388 this.send("newchat", { data: chat });
389 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
390 if (this.game.type == "corr" && this.st.user.id > 0)
391 this.updateCorrGame({ chat: chat });
393 clearChat: function() {
394 // Nothing more to do if game is live (chats not recorded)
395 if (this.game.type == "corr") {
396 if (!!this.game.mycolor) {
400 { data: { gid: this.game.id } }
403 this.$set(this.game, "chats", []);
406 getGameType: function(game) {
407 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
409 // Notify something after a new move (to opponent and me on MyGames page)
410 notifyMyGames: function(thing, data) {
415 targets: this.game.players.map(p => {
416 return { sid: p.sid, id: p.id };
421 showNextGame: function() {
422 // Did I play in current game? If not, add it to nextIds list
423 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
424 this.nextIds.unshift(this.game.id);
425 const nextGid = this.nextIds.pop();
427 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
429 askGameAgain: function() {
430 this.gameIsLoading = true;
431 const currentUrl = document.location.href;
432 const doAskGame = () => {
433 if (document.location.href != currentUrl) return; //page change
434 if (!this.gameRef.rid)
435 // This is my game: just reload.
438 // Just ask fullgame again (once!), this is much simpler.
439 // If this fails, the user could just reload page :/
440 this.send("askfullgame", { target: this.gameRef.rid });
442 // Delay of at least 2s between two game requests
443 const now = Date.now();
444 const delay = Math.max(2000 - (now - this.askGameTime), 0);
445 this.askGameTime = now;
446 setTimeout(doAskGame, delay);
448 socketMessageListener: function(msg) {
449 if (!this.conn) return;
450 const data = JSON.parse(msg.data);
453 data.sockIds.forEach(sid => {
454 if (sid != this.st.user.sid) {
455 this.people[sid] = { focus: true };
456 this.send("askidentity", { target: sid });
461 if (!this.people[data.from]) {
462 this.people[data.from] = { focus: true };
463 this.newConnect[data.from] = true; //for self multi-connects tests
464 this.send("askidentity", { target: data.from });
468 this.$delete(this.people, data.from);
471 let player = this.people[data.from];
474 this.$forceUpdate(); //TODO: shouldn't be required
479 let player = this.people[data.from];
481 player.focus = false;
482 this.$forceUpdate(); //TODO: shouldn't be required
487 // I logged in elsewhere:
489 alert(this.st.tr["New connexion detected: tab now offline"]);
491 case "askidentity": {
492 // Request for identification
494 // Decompose to avoid revealing email
495 name: this.st.user.name,
496 sid: this.st.user.sid,
499 this.send("identity", { data: me, target: data.from });
503 const user = data.data;
504 let player = this.people[user.sid];
505 // player.focus is already set
506 player.name = user.name;
508 this.$forceUpdate(); //TODO: shouldn't be required
509 // If I multi-connect, kill current connexion if no mark (I'm older)
510 if (this.newConnect[user.sid]) {
513 user.id == this.st.user.id &&
514 user.sid != this.st.user.sid &&
515 !this.killed[this.st.user.sid]
517 this.send("killme", { sid: this.st.user.sid });
518 this.killed[this.st.user.sid] = true;
520 delete this.newConnect[user.sid];
522 if (!this.killed[this.st.user.sid]) {
523 // Ask potentially missed last state, if opponent and I play
525 !!this.game.mycolor &&
526 this.game.type == "live" &&
527 this.game.score == "*" &&
528 this.game.players.some(p => p.sid == user.sid)
530 this.send("asklastate", { target: user.sid });
532 this.askLastate = setInterval(
534 // Ask at most 3 times:
535 // if no reply after that there should be a network issue.
539 !!this.people[user.sid]
541 this.send("asklastate", { target: user.sid });
544 clearInterval(this.askLastate);
554 // Send current (live) game if not asked by any of the players
556 this.game.type == "live" &&
557 this.game.players.every(p => p.sid != data.from[0])
562 players: this.game.players,
564 cadence: this.game.cadence,
565 score: this.game.score,
566 rid: this.st.user.sid //useful in Hall if I'm an observer
568 this.send("game", { data: myGame, target: data.from });
572 const gameToSend = Object.keys(this.game)
575 "id","fen","players","vid","cadence","fenStart","vname",
576 "moves","clocks","initime","score","drawOffer","rematchOffer"
580 obj[k] = this.game[k];
585 this.send("fullgame", { data: gameToSend, target: data.from });
588 // Callback "roomInit" to poll clients only after game is loaded
589 this.loadGame(data.data, this.roomInit);
592 // Sending informative last state if I played a move or score != "*"
593 // If the game or moves aren't loaded yet, delay the sending:
594 if (!this.game || !this.game.moves) this.lastateAsked = true;
595 else this.sendLastate(data.from);
598 // Got opponent infos about last move
599 this.gotLastate = true;
600 if (!data.data.nothing) {
601 this.lastate = data.data;
602 if (this.game.rendered)
603 // Game is rendered (Board component)
604 this.processLastate();
605 // Else: will be processed when game is ready
610 const movePlus = data.data;
611 const movesCount = this.game.moves.length;
612 if (movePlus.index > movesCount) {
613 // This can only happen if I'm an observer and missed a move.
614 if (this.gotMoveIdx < movePlus.index)
615 this.gotMoveIdx = movePlus.index;
616 if (!this.gameIsLoading) this.askGameAgain();
620 movePlus.index < movesCount ||
621 this.gotMoveIdx >= movePlus.index
623 // Opponent re-send but we already have the move:
624 // (maybe he didn't receive our pingback...)
625 this.send("gotmove", {data: movePlus.index, target: data.from});
627 this.gotMoveIdx = movePlus.index;
628 const receiveMyMove = (movePlus.color == this.game.mycolor);
629 if (!receiveMyMove && !!this.game.mycolor)
630 // Notify opponent that I got the move:
631 this.send("gotmove", {data: movePlus.index, target: data.from});
632 if (movePlus.cancelDrawOffer) {
633 // Opponent refuses draw
635 // NOTE for corr games: drawOffer reset by player in turn
637 this.game.type == "live" &&
638 !!this.game.mycolor &&
641 GameStorage.update(this.gameRef.id, { drawOffer: "" });
644 this.$refs["basegame"].play(movePlus.move, "received", null, true);
648 clock: movePlus.clock,
649 receiveMyMove: receiveMyMove
657 this.opponentGotMove = true;
658 // Now his clock starts running:
659 const oppIdx = ['w','b'].indexOf(this.vr.turn);
660 this.game.initime[oppIdx] = Date.now();
665 const score = data.side == "b" ? "1-0" : "0-1";
666 const side = data.side == "w" ? "White" : "Black";
667 this.gameOver(score, side + " surrender");
670 this.gameOver("?", "Stop");
673 this.gameOver("1/2", data.data);
676 // NOTE: observers don't know who offered draw
677 this.drawOffer = "received";
680 // NOTE: observers don't know who offered rematch
681 this.rematchOffer = data.data ? "received" : "";
684 // A game started, redirect if I'm playing in
685 const gameInfo = data.data;
686 const gameType = this.getGameType(gameInfo);
688 gameType == "live" &&
689 gameInfo.players.some(p => p.sid == this.st.user.sid)
691 this.addAndGotoLiveGame(gameInfo);
693 gameType == "corr" &&
694 gameInfo.players.some(p => p.id == this.st.user.id)
696 this.$router.push("/game/" + gameInfo.id);
699 if (gameInfo.cadence.indexOf('d') === -1) {
701 // Select sid of any of the online players:
703 gameInfo.players.forEach(p => {
704 if (!!this.people[p.sid]) onlineSid.push(p.sid);
706 urlRid += onlineSid[Math.floor(Math.random() * onlineSid.length)];
708 this.rematchId = gameInfo.id + urlRid;
709 document.getElementById("modalInfo").checked = true;
714 this.newChat = data.data;
715 if (!document.getElementById("modalChat").checked)
716 document.getElementById("chatBtn").classList.add("somethingnew");
720 socketCloseListener: function() {
721 this.conn = new WebSocket(this.connexionString);
722 this.conn.addEventListener("message", this.socketMessageListener);
723 this.conn.addEventListener("close", this.socketCloseListener);
725 updateCorrGame: function(obj, callback) {
731 gid: this.gameRef.id,
735 if (!!callback) callback();
740 sendLastate: function(target) {
742 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
743 this.game.score != "*" ||
744 this.drawOffer == "sent" ||
745 this.rematchOffer == "sent"
747 // Send our "last state" informations to opponent
748 const L = this.game.moves.length;
749 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
751 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
752 clock: this.game.clocks[myIdx],
753 // Since we played a move (or abort or resign),
754 // only drawOffer=="sent" is possible
755 drawSent: this.drawOffer == "sent",
756 rematchSent: this.rematchOffer == "sent",
757 score: this.game.score,
758 scoreMsg: this.game.scoreMsg,
760 initime: this.game.initime[1 - myIdx] //relevant only if I played
762 this.send("lastate", { data: myLastate, target: target });
764 this.send("lastate", { data: {nothing: true}, target: target });
767 // lastate was received, but maybe game wasn't ready yet:
768 processLastate: function() {
769 const data = this.lastate;
770 this.lastate = undefined; //security...
771 const L = this.game.moves.length;
772 if (data.movesCount > L) {
773 // Just got last move from him
774 this.$refs["basegame"].play(data.lastMove, "received", null, true);
775 this.processMove(data.lastMove, { clock: data.clock });
777 if (data.drawSent) this.drawOffer = "received";
778 if (data.rematchSent) this.rematchOffer = "received";
779 if (data.score != "*") {
781 if (this.game.score == "*")
782 this.gameOver(data.score, data.scoreMsg);
785 clickDraw: function() {
786 if (!this.game.mycolor) return; //I'm just spectator
787 if (["received", "threerep"].includes(this.drawOffer)) {
788 if (!confirm(this.st.tr["Accept draw?"])) return;
790 this.drawOffer == "received"
792 : "Three repetitions";
793 this.send("draw", { data: message });
794 this.gameOver("1/2", message);
795 } else if (this.drawOffer == "") {
796 // No effect if drawOffer == "sent"
797 if (this.game.mycolor != this.vr.turn) {
798 alert(this.st.tr["Draw offer only in your turn"]);
801 if (!confirm(this.st.tr["Offer draw?"])) return;
802 this.drawOffer = "sent";
803 this.send("drawoffer");
804 if (this.game.type == "live") {
807 { drawOffer: this.game.mycolor }
809 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
812 addAndGotoLiveGame: function(gameInfo, callback) {
813 const game = Object.assign(
817 // (other) Game infos: constant
818 fenStart: gameInfo.fen,
819 vname: this.game.vname,
821 // Game state (including FEN): will be updated
823 clocks: [-1, -1], //-1 = unstarted
824 initime: [0, 0], //initialized later
828 GameStorage.add(game, (err) => {
829 // No error expected.
831 if (this.st.settings.sound)
832 new Audio("/sounds/newgame.flac").play().catch(() => {});
833 if (!!callback) callback();
834 this.$router.push("/game/" + gameInfo.id);
838 clickRematch: function() {
839 if (!this.game.mycolor) return; //I'm just spectator
840 if (this.rematchOffer == "received") {
843 id: getRandString(), //ignored if corr
844 fen: V.GenRandInitFen(this.game.randomness),
845 players: this.game.players.reverse(),
847 cadence: this.game.cadence
849 const notifyNewGame = () => {
850 const oppsid = this.getOppsid(); //may be null
851 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
852 // To main Hall if corr game:
853 if (this.game.type == "corr")
854 this.send("newgame", { data: gameInfo });
855 // Also to MyGames page:
856 this.notifyMyGames("newgame", gameInfo);
858 if (this.game.type == "live")
859 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
866 // cid is useful to delete the challenge:
867 data: { gameInfo: gameInfo },
868 success: (response) => {
869 gameInfo.id = response.gameId;
871 this.$router.push("/game/" + response.gameId);
876 } else if (this.rematchOffer == "") {
877 this.rematchOffer = "sent";
878 this.send("rematchoffer", { data: true });
879 if (this.game.type == "live") {
882 { rematchOffer: this.game.mycolor }
884 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
885 } else if (this.rematchOffer == "sent") {
886 // Toggle rematch offer (on --> off)
887 this.rematchOffer = "";
888 this.send("rematchoffer", { data: false });
889 if (this.game.type == "live") {
894 } else this.updateCorrGame({ rematchOffer: 'n' });
897 abortGame: function() {
898 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
899 this.gameOver("?", "Stop");
903 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
905 this.send("resign", { data: this.game.mycolor });
906 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
907 const side = this.game.mycolor == "w" ? "White" : "Black";
908 this.gameOver(score, side + " surrender");
910 // 3 cases for loading a game:
911 // - from indexedDB (running or completed live game I play)
912 // - from server (one correspondance game I play[ed] or not)
913 // - from remote peer (one live game I don't play, finished or not)
914 loadGame: function(game, callback) {
915 const afterRetrieval = async (game) => {
916 const vModule = await import("@/variants/" + game.vname + ".js");
917 window.V = vModule.VariantRules;
918 this.vr = new V(game.fen);
919 const gtype = this.getGameType(game);
920 const tc = extractTime(game.cadence);
921 const myIdx = game.players.findIndex(p => {
922 return p.sid == this.st.user.sid || p.id == this.st.user.id;
924 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
925 if (!game.chats) game.chats = []; //live games don't have chat history
926 if (gtype == "corr") {
927 // NOTE: clocks in seconds, initime in milliseconds
928 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
929 game.clocks = [tc.mainTime, tc.mainTime];
930 const L = game.moves.length;
931 if (game.score == "*") {
932 // Set clocks + initime
933 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
934 if (L >= 1) game.initime[L % 2] = game.moves[L-1].played;
935 // NOTE: game.clocks shouldn't be computed right now:
936 // job will be done in re_setClocks() called soon below.
938 // Sort chat messages from newest to oldest
939 game.chats.sort((c1, c2) => {
940 return c2.added - c1.added;
942 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
943 // Did a chat message arrive after my last move?
945 if (L == 1 && myIdx == 0)
946 dtLastMove = game.moves[0].played;
949 // It's now white turn
950 dtLastMove = game.moves[L-1-(1-myIdx)].played;
953 dtLastMove = game.moves[L-1-myIdx].played;
956 if (dtLastMove < game.chats[0].added)
957 document.getElementById("chatBtn").classList.add("somethingnew");
959 // Now that we used idx and played, re-format moves as for live games
960 game.moves = game.moves.map(m => m.squares);
962 if (gtype == "live" && game.clocks[0] < 0) {
963 // Game is unstarted. clocks and initime are ignored until move 2
964 game.clocks = [tc.mainTime, tc.mainTime];
965 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
967 // I play in this live game
968 GameStorage.update(game.id, {
970 initime: game.initime
974 // TODO: merge next 2 "if" conditions
975 if (!!game.drawOffer) {
976 if (game.drawOffer == "t")
978 this.drawOffer = "threerep";
980 // Draw offered by any of the players:
981 if (myIdx < 0) this.drawOffer = "received";
983 // I play in this game:
985 (game.drawOffer == "w" && myIdx == 0) ||
986 (game.drawOffer == "b" && myIdx == 1)
988 this.drawOffer = "sent";
989 else this.drawOffer = "received";
993 if (!!game.rematchOffer) {
994 if (myIdx < 0) this.rematchOffer = "received";
996 // I play in this game:
998 (game.rematchOffer == "w" && myIdx == 0) ||
999 (game.rematchOffer == "b" && myIdx == 1)
1001 this.rematchOffer = "sent";
1002 else this.rematchOffer = "received";
1005 this.repeat = {}; //reset: scan past moves' FEN:
1007 let vr_tmp = new V(game.fenStart);
1009 game.moves.forEach(m => {
1010 playMove(m, vr_tmp);
1011 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1012 this.repeat[fenIdx] = this.repeat[fenIdx]
1013 ? this.repeat[fenIdx] + 1
1016 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1017 this.game = Object.assign(
1018 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1021 increment: tc.increment,
1023 // opponent sid not strictly required (or available), but easier
1024 // at least oppsid or oppid is available anyway:
1025 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1026 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1030 this.$refs["basegame"].re_setVariables(this.game);
1031 if (!this.gameIsLoading) {
1033 this.gotMoveIdx = game.moves.length - 1;
1034 // If we arrive here after 'nextGame' action, the board might be hidden
1035 let boardDiv = document.querySelector(".game");
1036 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1037 boardDiv.style.visibility = "visible";
1039 this.re_setClocks();
1040 this.$nextTick(() => {
1041 this.game.rendered = true;
1042 // Did lastate arrive before game was rendered?
1043 if (this.lastate) this.processLastate();
1045 if (this.lastateAsked) {
1046 this.lastateAsked = false;
1047 this.sendLastate(game.oppsid);
1049 if (this.gameIsLoading) {
1050 this.gameIsLoading = false;
1051 if (this.gotMoveIdx >= game.moves.length)
1052 // Some moves arrived meanwhile...
1053 this.askGameAgain();
1055 if (!!callback) callback();
1058 afterRetrieval(game);
1061 if (this.gameRef.rid) {
1062 // Remote live game: forgetting about callback func... (TODO: design)
1063 this.send("askfullgame", { target: this.gameRef.rid });
1065 // Local or corr game on server.
1066 // NOTE: afterRetrieval() is never called if game not found
1067 const gid = this.gameRef.id;
1068 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
1069 // corr games identifiers are integers
1077 g.moves.forEach(m => {
1078 m.squares = JSON.parse(m.squares);
1087 GameStorage.get(this.gameRef.id, afterRetrieval);
1090 re_setClocks: function() {
1091 if (this.game.moves.length < 2 || this.game.score != "*") {
1092 // 1st move not completed yet, or game over: freeze time
1093 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1096 const currentTurn = this.vr.turn;
1097 const currentMovesCount = this.game.moves.length;
1098 const colorIdx = ["w", "b"].indexOf(currentTurn);
1100 this.game.clocks[colorIdx] -
1101 (Date.now() - this.game.initime[colorIdx]) / 1000;
1102 this.virtualClocks = [0, 1].map(i => {
1104 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
1105 return ppt(this.game.clocks[i] - removeTime).split(':');
1107 this.clockUpdate = setInterval(
1111 this.game.moves.length > currentMovesCount ||
1112 this.game.score != "*"
1114 clearInterval(this.clockUpdate);
1117 currentTurn == "w" ? "0-1" : "1-0",
1124 ppt(Math.max(0, --countdown)).split(':')
1130 // Update variables and storage after a move:
1131 processMove: function(move, data) {
1132 if (!data) data = {};
1133 const moveCol = this.vr.turn;
1134 const doProcessMove = () => {
1135 const colorIdx = ["w", "b"].indexOf(moveCol);
1136 const nextIdx = 1 - colorIdx;
1137 const origMovescount = this.game.moves.length;
1138 let addTime = 0; //for live games
1139 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1140 if (this.drawOffer == "received")
1142 this.drawOffer = "";
1143 if (this.game.type == "live" && origMovescount >= 2) {
1144 const elapsed = Date.now() - this.game.initime[colorIdx];
1145 // elapsed time is measured in milliseconds
1146 addTime = this.game.increment - elapsed / 1000;
1149 // Update current game object:
1150 playMove(move, this.vr);
1151 // The move is played: stop clock
1152 clearInterval(this.clockUpdate);
1154 // Received move, score has not been computed in BaseGame (!!noemit)
1155 const score = this.vr.getCurrentScore();
1156 if (score != "*") this.gameOver(score);
1158 this.game.moves.push(move);
1159 this.game.fen = this.vr.getFen();
1160 if (this.game.type == "live") {
1161 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
1162 else this.game.clocks[colorIdx] += addTime;
1164 // 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,
1226 // Code "n" for "None" to force reset (otherwise it's ignored)
1227 drawOffer: drawCode || "n"
1231 const updateStorage = () => {
1232 GameStorage.update(this.gameRef.id, {
1234 move: filtered_move,
1235 moveIdx: origMovescount,
1236 clocks: this.game.clocks,
1237 initime: this.game.initime,
1241 // The active tab can update storage immediately
1242 if (!document.hidden) updateStorage();
1243 // Small random delay otherwise
1244 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1247 // Send move ("newmove" event) to people in the room (if our turn)
1248 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1250 move: filtered_move,
1251 index: origMovescount,
1252 // color is required to check if this is my move (if several tabs opened)
1254 cancelDrawOffer: this.drawOffer == ""
1256 if (this.game.type == "live")
1257 sendMove["clock"] = this.game.clocks[colorIdx];
1258 this.opponentGotMove = false;
1259 this.send("newmove", {data: sendMove});
1260 // If the opponent doesn't reply gotmove soon enough, re-send move:
1261 // Do this at most 2 times, because mpore would mean network issues,
1262 // opponent would then be expected to disconnect/reconnect.
1264 const currentUrl = document.location.href;
1265 this.retrySendmove = setInterval(
1269 this.opponentGotMove ||
1270 document.location.href != currentUrl //page change
1272 clearInterval(this.retrySendmove);
1275 const oppsid = this.getOppsid();
1277 // Opponent is disconnected: he'll ask last state
1278 clearInterval(this.retrySendmove);
1280 this.send("newmove", { data: sendMove, target: oppsid });
1288 // Not my move or I'm an observer: just start other player's clock
1289 this.re_setClocks();
1292 this.game.type == "corr" &&
1293 moveCol == this.game.mycolor &&
1296 let boardDiv = document.querySelector(".game");
1297 const afterSetScore = () => {
1299 if (this.st.settings.gotonext && this.nextIds.length > 0)
1300 this.showNextGame();
1302 // The board might have been hidden:
1303 if (boardDiv.style.visibility == "hidden")
1304 boardDiv.style.visibility = "visible";
1307 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1308 // We may play several moves in a row: in case of, remove listener:
1309 let elClone = el.cloneNode(true);
1310 el.parentNode.replaceChild(elClone, el);
1311 elClone.addEventListener(
1314 document.getElementById("modalConfirm").checked = false;
1315 if (!!data.score && data.score != "*")
1317 this.gameOver(data.score, null, afterSetScore);
1318 else afterSetScore();
1321 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1322 V.PlayOnBoard(this.vr.board, move);
1323 const position = this.vr.getBaseFen();
1324 V.UndoOnBoard(this.vr.board, move);
1325 if (["all","byrow"].includes(V.ShowMoves)) {
1326 this.curDiag = getDiagram({
1328 orientation: V.CanFlip ? this.game.mycolor : "w"
1330 document.querySelector("#confirmDiv > .card").style.width =
1331 boardDiv.offsetWidth + "px";
1333 // Incomplete information: just ask confirmation
1334 // Hide the board, because otherwise it could reveal infos
1335 boardDiv.style.visibility = "hidden";
1336 this.moveNotation = getFullNotation(move);
1338 document.getElementById("modalConfirm").checked = true;
1342 if (!!data.score && data.score != "*")
1343 this.gameOver(data.score, null, doProcessMove);
1344 else doProcessMove();
1347 cancelMove: function() {
1348 let boardDiv = document.querySelector(".game");
1349 if (boardDiv.style.visibility == "hidden")
1350 boardDiv.style.visibility = "visible";
1351 document.getElementById("modalConfirm").checked = false;
1352 this.$refs["basegame"].cancelLastMove();
1354 // In corr games, callback to change page only after score is set:
1355 gameOver: function(score, scoreMsg, callback) {
1356 this.game.score = score;
1357 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1358 this.game.scoreMsg = scoreMsg;
1359 this.$set(this.game, "scoreMsg", scoreMsg);
1360 const myIdx = this.game.players.findIndex(p => {
1361 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1364 // OK, I play in this game
1369 if (this.game.type == "live") {
1370 GameStorage.update(this.gameRef.id, scoreObj);
1371 if (!!callback) callback();
1373 else this.updateCorrGame(scoreObj, callback);
1374 // Notify the score to main Hall. TODO: only one player (currently double send)
1375 this.send("result", { gid: this.game.id, score: score });
1376 // Also to MyGames page (TODO: doubled as well...)
1380 gid: this.gameRef.id,
1385 else if (!!callback) callback();
1391 <style lang="sass" scoped>
1397 background-color: lightgreen
1409 @media screen and (min-width: 768px)
1412 @media screen and (max-width: 767px)
1417 display: inline-block
1421 display: inline-block
1423 display: inline-flex
1427 @media screen and (max-width: 767px)
1430 @media screen and (max-width: 767px)
1433 @media screen and (min-width: 768px)
1445 background-color: #edda99
1447 display: inline-block
1456 display: inline-block
1469 animation: blink-animation 2s steps(3, start) infinite
1470 @keyframes blink-animation
1475 display: inline-block
1487 .draw-sent, .draw-sent:hover
1488 background-color: lightyellow
1490 .draw-received, .draw-received:hover
1491 background-color: lightgreen
1493 .draw-threerep, .draw-threerep:hover
1494 background-color: #e4d1fc
1496 .rematch-sent, .rematch-sent:hover
1497 background-color: lightyellow
1499 .rematch-received, .rematch-received:hover
1500 background-color: lightgreen
1503 background-color: #c5fefe
1516 background-color: lightgreen
1518 background-color: red