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")
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
167 people: {}, //players + observers
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);
219 ["chatWrap", "infoDiv"].forEach(eltName => {
220 document.getElementById(eltName)
221 .addEventListener("click", processModalClick);
223 if ("ontouchstart" in window) {
224 // Disable tooltips on smartphones:
225 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
226 elt.classList.remove("tooltip");
230 beforeDestroy: function() {
231 document.removeEventListener('visibilitychange', this.visibilityChange);
232 this.cleanBeforeDestroy();
235 visibilityChange: function() {
236 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
238 document.visibilityState == "visible"
243 atCreation: function() {
244 // 0] (Re)Set variables
245 this.gameRef.id = this.$route.params["id"];
246 // rid = remote ID to find an observed live game,
247 // next = next corr games IDs to navigate faster
248 // (Both might be undefined)
249 this.gameRef.rid = this.$route.query["rid"];
250 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
251 // Always add myself to players' list
252 const my = this.st.user;
263 players: [{ name: "" }, { name: "" }],
267 let chatComp = this.$refs["chatcomp"];
268 if (!!chatComp) chatComp.chats = [];
269 this.virtualClocks = [[0,0], [0,0]];
272 this.lastateAsked = false;
273 this.rematchOffer = "";
274 this.lastate = undefined;
276 this.roomInitialized = false;
277 this.askGameTime = 0;
278 this.gameIsLoading = false;
279 this.gotLastate = false;
280 this.gotMoveIdx = -1;
281 this.opponentGotMove = false;
282 this.askLastate = null;
283 this.retrySendmove = null;
284 this.clockUpdate = null;
285 this.newConnect = {};
287 // 1] Initialize connection
288 this.connexionString =
297 // Discard potential "/?next=[...]" for page indication:
298 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
299 this.conn = new WebSocket(this.connexionString);
300 this.conn.onmessage = this.socketMessageListener;
301 this.conn.onclose = this.socketCloseListener;
302 // Socket init required before loading remote game:
303 const socketInit = callback => {
304 if (!!this.conn && this.conn.readyState == 1)
308 // Socket not ready yet (initial loading)
309 // NOTE: it's important to call callback without arguments,
310 // otherwise first arg is Websocket object and loadGame fails.
311 this.conn.onopen = () => callback();
313 if (!this.gameRef.rid)
314 // Game stored locally or on server
315 this.loadGame(null, () => socketInit(this.roomInit));
317 // Game stored remotely: need socket to retrieve it
318 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
319 // --> It will be given when receiving "fullgame" socket event.
320 socketInit(this.loadGame);
322 cleanBeforeDestroy: function() {
323 if (!!this.askLastate)
324 clearInterval(this.askLastate);
325 if (!!this.retrySendmove)
326 clearInterval(this.retrySendmove);
327 if (!!this.clockUpdate)
328 clearInterval(this.clockUpdate);
329 this.send("disconnect");
331 roomInit: function() {
332 if (!this.roomInitialized) {
333 // Notify the room only now that I connected, because
334 // messages might be lost otherwise (if game loading is slow)
335 this.send("connect");
336 this.send("pollclients");
337 // We may ask fullgame several times if some moves are lost,
338 // but room should be init only once:
339 this.roomInitialized = true;
342 send: function(code, obj) {
344 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
346 isConnected: function(index) {
347 const player = this.game.players[index];
348 // Is it me ? In this case no need to bother with focus
349 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
350 // Still have to check for name (because of potential multi-accounts
351 // on same browser, although this should be rare...)
352 return (!this.st.user.name || this.st.user.name == player.name);
353 // Try to find a match in people:
357 Object.keys(this.people).some(sid =>
358 sid == player.sid && this.people[sid].focus)
363 Object.values(this.people).some(p =>
364 p.id == player.uid && p.focus)
368 getOppsid: function() {
369 let oppsid = this.game.oppsid;
371 oppsid = Object.keys(this.people).find(
372 sid => this.people[sid].id == this.game.oppid
375 // oppsid is useful only if opponent is online:
376 if (!!oppsid && !!this.people[oppsid]) return oppsid;
379 resetChatColor: function() {
380 // TODO: this is called twice, once on opening an once on closing
381 document.getElementById("chatBtn").classList.remove("somethingnew");
383 processChat: function(chat) {
384 this.send("newchat", { data: chat });
385 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
386 if (this.game.type == "corr" && this.st.user.id > 0)
387 this.updateCorrGame({ chat: chat });
389 clearChat: function() {
390 // Nothing more to do if game is live (chats not recorded)
391 if (this.game.type == "corr") {
392 if (!!this.game.mycolor) {
396 { data: { gid: this.game.id } }
399 this.$set(this.game, "chats", []);
402 getGameType: function(game) {
403 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
405 // Notify something after a new move (to opponent and me on MyGames page)
406 notifyMyGames: function(thing, data) {
411 targets: this.game.players.map(p => {
412 return { sid: p.sid, uid: p.uid };
417 showNextGame: function() {
418 // Did I play in current game? If not, add it to nextIds list
419 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
420 this.nextIds.unshift(this.game.id);
421 const nextGid = this.nextIds.pop();
423 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
425 askGameAgain: function() {
426 this.gameIsLoading = true;
427 const currentUrl = document.location.href;
428 const doAskGame = () => {
429 if (document.location.href != currentUrl) return; //page change
430 if (!this.gameRef.rid)
431 // This is my game: just reload.
434 // Just ask fullgame again (once!), this is much simpler.
435 // If this fails, the user could just reload page :/
436 this.send("askfullgame", { target: this.gameRef.rid });
438 // Delay of at least 2s between two game requests
439 const now = Date.now();
440 const delay = Math.max(2000 - (now - this.askGameTime), 0);
441 this.askGameTime = now;
442 setTimeout(doAskGame, delay);
444 socketMessageListener: function(msg) {
445 if (!this.conn) return;
446 const data = JSON.parse(msg.data);
449 data.sockIds.forEach(sid => {
450 if (sid != this.st.user.sid) {
451 this.people[sid] = { focus: true };
452 this.send("askidentity", { target: sid });
457 if (!this.people[data.from]) {
458 this.people[data.from] = { focus: true };
459 this.newConnect[data.from] = true; //for self multi-connects tests
460 this.send("askidentity", { target: data.from });
464 this.$delete(this.people, data.from);
467 let player = this.people[data.from];
470 this.$forceUpdate(); //TODO: shouldn't be required
475 let player = this.people[data.from];
477 player.focus = false;
478 this.$forceUpdate(); //TODO: shouldn't be required
483 // I logged in elsewhere:
485 alert(this.st.tr["New connexion detected: tab now offline"]);
487 case "askidentity": {
488 // Request for identification
490 // Decompose to avoid revealing email
491 name: this.st.user.name,
492 sid: this.st.user.sid,
495 this.send("identity", { data: me, target: data.from });
499 const user = data.data;
500 let player = this.people[user.sid];
501 // player.focus is already set
502 player.name = user.name;
504 this.$forceUpdate(); //TODO: shouldn't be required
505 // If I multi-connect, kill current connexion if no mark (I'm older)
506 if (this.newConnect[user.sid]) {
509 user.id == this.st.user.id &&
510 user.sid != this.st.user.sid &&
511 !this.killed[this.st.user.sid]
513 this.send("killme", { sid: this.st.user.sid });
514 this.killed[this.st.user.sid] = true;
516 delete this.newConnect[user.sid];
518 if (!this.killed[this.st.user.sid]) {
519 // Ask potentially missed last state, if opponent and I play
521 !!this.game.mycolor &&
522 this.game.type == "live" &&
523 this.game.score == "*" &&
524 this.game.players.some(p => p.sid == user.sid)
526 this.send("asklastate", { target: user.sid });
528 this.askLastate = setInterval(
530 // Ask at most 3 times:
531 // if no reply after that there should be a network issue.
535 !!this.people[user.sid]
537 this.send("asklastate", { target: user.sid });
540 clearInterval(this.askLastate);
550 // Send current (live) game if not asked by any of the players
552 this.game.type == "live" &&
553 this.game.players.every(p => p.sid != data.from[0])
558 players: this.game.players,
560 cadence: this.game.cadence,
561 score: this.game.score,
562 rid: this.st.user.sid //useful in Hall if I'm an observer
564 this.send("game", { data: myGame, target: data.from });
568 const gameToSend = Object.keys(this.game)
571 "id","fen","players","vid","cadence","fenStart","vname",
572 "moves","clocks","initime","score","drawOffer","rematchOffer"
576 obj[k] = this.game[k];
581 this.send("fullgame", { data: gameToSend, target: data.from });
584 // Callback "roomInit" to poll clients only after game is loaded
585 this.loadGame(data.data, this.roomInit);
588 // Sending informative last state if I played a move or score != "*"
589 // If the game or moves aren't loaded yet, delay the sending:
590 if (!this.game || !this.game.moves) this.lastateAsked = true;
591 else this.sendLastate(data.from);
594 // Got opponent infos about last move
595 this.gotLastate = true;
596 if (!data.data.nothing) {
597 this.lastate = data.data;
598 if (this.game.rendered)
599 // Game is rendered (Board component)
600 this.processLastate();
601 // Else: will be processed when game is ready
606 const movePlus = data.data;
607 const movesCount = this.game.moves.length;
608 if (movePlus.index > movesCount) {
609 // This can only happen if I'm an observer and missed a move.
610 if (this.gotMoveIdx < movePlus.index)
611 this.gotMoveIdx = movePlus.index;
612 if (!this.gameIsLoading) this.askGameAgain();
616 movePlus.index < movesCount ||
617 this.gotMoveIdx >= movePlus.index
619 // Opponent re-send but we already have the move:
620 // (maybe he didn't receive our pingback...)
621 this.send("gotmove", {data: movePlus.index, target: data.from});
623 this.gotMoveIdx = movePlus.index;
624 const receiveMyMove = (movePlus.color == this.game.mycolor);
625 if (!receiveMyMove && !!this.game.mycolor)
626 // Notify opponent that I got the move:
627 this.send("gotmove", {data: movePlus.index, target: data.from});
628 if (movePlus.cancelDrawOffer) {
629 // Opponent refuses draw
631 // NOTE for corr games: drawOffer reset by player in turn
633 this.game.type == "live" &&
634 !!this.game.mycolor &&
637 GameStorage.update(this.gameRef.id, { drawOffer: "" });
640 this.$refs["basegame"].play(movePlus.move, "received", null, true);
644 clock: movePlus.clock,
645 receiveMyMove: receiveMyMove
653 this.opponentGotMove = true;
654 // Now his clock starts running:
655 const oppIdx = ['w','b'].indexOf(this.vr.turn);
656 this.game.initime[oppIdx] = Date.now();
661 const score = data.side == "b" ? "1-0" : "0-1";
662 const side = data.side == "w" ? "White" : "Black";
663 this.gameOver(score, side + " surrender");
666 this.gameOver("?", "Stop");
669 this.gameOver("1/2", data.data);
672 // NOTE: observers don't know who offered draw
673 this.drawOffer = "received";
676 // NOTE: observers don't know who offered rematch
677 this.rematchOffer = data.data ? "received" : "";
680 // A game started, redirect if I'm playing in
681 const gameInfo = data.data;
682 const gameType = this.getGameType(gameInfo);
684 gameType == "live" &&
685 gameInfo.players.some(p => p.sid == this.st.user.sid)
687 this.addAndGotoLiveGame(gameInfo);
689 gameType == "corr" &&
690 gameInfo.players.some(p => p.uid == this.st.user.id)
692 this.$router.push("/game/" + gameInfo.id);
695 if (gameInfo.cadence.indexOf('d') === -1) {
697 // Select sid of any of the online players:
699 gameInfo.players.forEach(p => {
700 if (!!this.people[p.sid]) onlineSid.push(p.sid);
702 urlRid += onlineSid[Math.floor(Math.random() * onlineSid.length)];
705 this.st.tr["Rematch in progress:"] +
706 " <a href='#/game/" +
707 gameInfo.id + urlRid +
710 gameInfo.id + urlRid +
712 document.getElementById("modalInfo").checked = true;
717 this.newChat = data.data;
718 if (!document.getElementById("modalChat").checked)
719 document.getElementById("chatBtn").classList.add("somethingnew");
723 socketCloseListener: function() {
724 this.conn = new WebSocket(this.connexionString);
725 this.conn.addEventListener("message", this.socketMessageListener);
726 this.conn.addEventListener("close", this.socketCloseListener);
728 updateCorrGame: function(obj, callback) {
734 gid: this.gameRef.id,
738 if (!!callback) callback();
743 sendLastate: function(target) {
745 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
746 this.game.score != "*" ||
747 this.drawOffer == "sent" ||
748 this.rematchOffer == "sent"
750 // Send our "last state" informations to opponent
751 const L = this.game.moves.length;
752 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
754 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
755 clock: this.game.clocks[myIdx],
756 // Since we played a move (or abort or resign),
757 // only drawOffer=="sent" is possible
758 drawSent: this.drawOffer == "sent",
759 rematchSent: this.rematchOffer == "sent",
760 score: this.game.score,
761 scoreMsg: this.game.scoreMsg,
763 initime: this.game.initime[1 - myIdx] //relevant only if I played
765 this.send("lastate", { data: myLastate, target: target });
767 this.send("lastate", { data: {nothing: true}, target: target });
770 // lastate was received, but maybe game wasn't ready yet:
771 processLastate: function() {
772 const data = this.lastate;
773 this.lastate = undefined; //security...
774 const L = this.game.moves.length;
775 if (data.movesCount > L) {
776 // Just got last move from him
777 this.$refs["basegame"].play(data.lastMove, "received", null, true);
778 this.processMove(data.lastMove, { clock: data.clock });
780 if (data.drawSent) this.drawOffer = "received";
781 if (data.rematchSent) this.rematchOffer = "received";
782 if (data.score != "*") {
784 if (this.game.score == "*")
785 this.gameOver(data.score, data.scoreMsg);
788 clickDraw: function() {
789 if (!this.game.mycolor) return; //I'm just spectator
790 if (["received", "threerep"].includes(this.drawOffer)) {
791 if (!confirm(this.st.tr["Accept draw?"])) return;
793 this.drawOffer == "received"
795 : "Three repetitions";
796 this.send("draw", { data: message });
797 this.gameOver("1/2", message);
798 } else if (this.drawOffer == "") {
799 // No effect if drawOffer == "sent"
800 if (this.game.mycolor != this.vr.turn) {
801 alert(this.st.tr["Draw offer only in your turn"]);
804 if (!confirm(this.st.tr["Offer draw?"])) return;
805 this.drawOffer = "sent";
806 this.send("drawoffer");
807 if (this.game.type == "live") {
810 { drawOffer: this.game.mycolor }
812 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
815 addAndGotoLiveGame: function(gameInfo, callback) {
816 const game = Object.assign(
820 // (other) Game infos: constant
821 fenStart: gameInfo.fen,
822 vname: this.game.vname,
824 // Game state (including FEN): will be updated
826 clocks: [-1, -1], //-1 = unstarted
827 initime: [0, 0], //initialized later
831 GameStorage.add(game, (err) => {
832 // No error expected.
834 if (this.st.settings.sound)
835 new Audio("/sounds/newgame.flac").play().catch(() => {});
837 this.$router.push("/game/" + gameInfo.id);
841 clickRematch: function() {
842 if (!this.game.mycolor) return; //I'm just spectator
843 if (this.rematchOffer == "received") {
846 id: getRandString(), //ignored if corr
847 fen: V.GenRandInitFen(this.game.randomness),
848 players: this.game.players.reverse(),
850 cadence: this.game.cadence
852 const notifyNewGame = () => {
853 let oppsid = this.getOppsid(); //may be null
854 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
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.uid == 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 if (game.players[0].color == "b") {
928 // Adopt the same convention for live and corr games: [0] = white
929 [game.players[0], game.players[1]] = [
934 // NOTE: clocks in seconds, initime in milliseconds
935 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
936 game.clocks = [tc.mainTime, tc.mainTime];
937 const L = game.moves.length;
938 if (game.score == "*") {
939 // Set clocks + initime
940 game.initime = [0, 0];
942 const gameLastupdate = game.moves[L-1].played;
943 game.initime[L % 2] = gameLastupdate;
946 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
950 // Sort chat messages from newest to oldest
951 game.chats.sort((c1, c2) => {
952 return c2.added - c1.added;
954 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
955 // Did a chat message arrive after my last move?
957 if (L == 1 && myIdx == 0)
958 dtLastMove = game.moves[0].played;
961 // It's now white turn
962 dtLastMove = game.moves[L-1-(1-myIdx)].played;
965 dtLastMove = game.moves[L-1-myIdx].played;
968 if (dtLastMove < game.chats[0].added)
969 document.getElementById("chatBtn").classList.add("somethingnew");
971 // Now that we used idx and played, re-format moves as for live games
972 game.moves = game.moves.map(m => m.squares);
974 if (gtype == "live" && game.clocks[0] < 0) {
976 game.clocks = [tc.mainTime, tc.mainTime];
977 if (game.score == "*") {
978 game.initime[0] = Date.now();
980 // I play in this live game; corr games don't have clocks+initime
981 GameStorage.update(game.id, {
983 initime: game.initime
988 // TODO: merge next 2 "if" conditions
989 if (!!game.drawOffer) {
990 if (game.drawOffer == "t")
992 this.drawOffer = "threerep";
994 // Draw offered by any of the players:
995 if (myIdx < 0) this.drawOffer = "received";
997 // I play in this game:
999 (game.drawOffer == "w" && myIdx == 0) ||
1000 (game.drawOffer == "b" && myIdx == 1)
1002 this.drawOffer = "sent";
1003 else this.drawOffer = "received";
1007 if (!!game.rematchOffer) {
1008 if (myIdx < 0) this.rematchOffer = "received";
1010 // I play in this game:
1012 (game.rematchOffer == "w" && myIdx == 0) ||
1013 (game.rematchOffer == "b" && myIdx == 1)
1015 this.rematchOffer = "sent";
1016 else this.rematchOffer = "received";
1019 this.repeat = {}; //reset: scan past moves' FEN:
1021 let vr_tmp = new V(game.fenStart);
1023 game.moves.forEach(m => {
1024 playMove(m, vr_tmp);
1025 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1026 this.repeat[fenIdx] = this.repeat[fenIdx]
1027 ? this.repeat[fenIdx] + 1
1030 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1031 this.game = Object.assign(
1032 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1035 increment: tc.increment,
1037 // opponent sid not strictly required (or available), but easier
1038 // at least oppsid or oppid is available anyway:
1039 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1040 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
1044 if (this.gameIsLoading)
1045 // Re-load game because we missed some moves:
1046 // artificially reset BaseGame (required if moves arrived in wrong order)
1047 this.$refs["basegame"].re_setVariables();
1050 this.gotMoveIdx = game.moves.length - 1;
1051 // If we arrive here after 'nextGame' action, the board might be hidden
1052 let boardDiv = document.querySelector(".game");
1053 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1054 boardDiv.style.visibility = "visible";
1056 this.re_setClocks();
1057 this.$nextTick(() => {
1058 this.game.rendered = true;
1059 // Did lastate arrive before game was rendered?
1060 if (this.lastate) this.processLastate();
1062 if (this.lastateAsked) {
1063 this.lastateAsked = false;
1064 this.sendLastate(game.oppsid);
1066 if (this.gameIsLoading) {
1067 this.gameIsLoading = false;
1068 if (this.gotMoveIdx >= game.moves.length)
1069 // Some moves arrived meanwhile...
1070 this.askGameAgain();
1072 if (!!callback) callback();
1075 afterRetrieval(game);
1078 if (this.gameRef.rid) {
1079 // Remote live game: forgetting about callback func... (TODO: design)
1080 this.send("askfullgame", { target: this.gameRef.rid });
1082 // Local or corr game on server.
1083 // NOTE: afterRetrieval() is never called if game not found
1084 const gid = this.gameRef.id;
1085 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
1086 // corr games identifiers are integers
1094 g.moves.forEach(m => {
1095 m.squares = JSON.parse(m.squares);
1104 GameStorage.get(this.gameRef.id, afterRetrieval);
1107 re_setClocks: function() {
1108 if (this.game.moves.length < 2 || this.game.score != "*") {
1109 // 1st move not completed yet, or game over: freeze time
1110 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1113 const currentTurn = this.vr.turn;
1114 const currentMovesCount = this.game.moves.length;
1115 const colorIdx = ["w", "b"].indexOf(currentTurn);
1117 this.game.clocks[colorIdx] -
1118 (Date.now() - this.game.initime[colorIdx]) / 1000;
1119 this.virtualClocks = [0, 1].map(i => {
1121 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
1122 return ppt(this.game.clocks[i] - removeTime).split(':');
1124 this.clockUpdate = setInterval(
1128 this.game.moves.length > currentMovesCount ||
1129 this.game.score != "*"
1131 clearInterval(this.clockUpdate);
1134 currentTurn == "w" ? "0-1" : "1-0",
1141 ppt(Math.max(0, --countdown)).split(':')
1147 // Update variables and storage after a move:
1148 processMove: function(move, data) {
1149 if (!data) data = {};
1150 const moveCol = this.vr.turn;
1151 const doProcessMove = () => {
1152 const colorIdx = ["w", "b"].indexOf(moveCol);
1153 const nextIdx = 1 - colorIdx;
1154 const origMovescount = this.game.moves.length;
1155 let addTime = 0; //for live games
1156 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1157 if (this.drawOffer == "received")
1159 this.drawOffer = "";
1160 if (this.game.type == "live" && origMovescount >= 2) {
1161 const elapsed = Date.now() - this.game.initime[colorIdx];
1162 // elapsed time is measured in milliseconds
1163 addTime = this.game.increment - elapsed / 1000;
1166 // Update current game object:
1167 playMove(move, this.vr);
1168 // The move is played: stop clock
1169 clearInterval(this.clockUpdate);
1171 // Received move, score has not been computed in BaseGame (!!noemit)
1172 const score = this.vr.getCurrentScore();
1173 if (score != "*") this.gameOver(score);
1175 this.game.moves.push(move);
1176 this.game.fen = this.vr.getFen();
1177 if (this.game.type == "live") {
1178 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
1179 else this.game.clocks[colorIdx] += addTime;
1181 // In corr games, just reset clock to mainTime:
1183 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1185 // NOTE: opponent's initime is reset after "gotmove" is received
1187 !this.game.mycolor ||
1188 moveCol != this.game.mycolor ||
1189 !!data.receiveMyMove
1191 this.game.initime[nextIdx] = Date.now();
1193 // If repetition detected, consider that a draw offer was received:
1194 const fenObj = this.vr.getFenForRepeat();
1195 this.repeat[fenObj] =
1196 !!this.repeat[fenObj]
1197 ? this.repeat[fenObj] + 1
1199 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1200 else if (this.drawOffer == "threerep") this.drawOffer = "";
1201 if (!!this.game.mycolor && !data.receiveMyMove) {
1202 // NOTE: 'var' to see that variable outside this block
1203 var filtered_move = getFilteredMove(move);
1205 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1206 // Notify turn on MyGames page:
1210 gid: this.gameRef.id,
1215 // Since corr games are stored at only one location, update should be
1216 // done only by one player for each move:
1218 !!this.game.mycolor &&
1219 !data.receiveMyMove &&
1220 (this.game.type == "live" || moveCol == this.game.mycolor)
1223 switch (this.drawOffer) {
1228 drawCode = this.game.mycolor;
1231 drawCode = V.GetOppCol(this.game.mycolor);
1234 if (this.game.type == "corr") {
1235 // corr: only move, fen and score
1236 this.updateCorrGame({
1239 squares: filtered_move,
1243 // Code "n" for "None" to force reset (otherwise it's ignored)
1244 drawOffer: drawCode || "n"
1248 const updateStorage = () => {
1249 GameStorage.update(this.gameRef.id, {
1251 move: filtered_move,
1252 moveIdx: origMovescount,
1253 clocks: this.game.clocks,
1254 initime: this.game.initime,
1258 // The active tab can update storage immediately
1259 if (!document.hidden) updateStorage();
1260 // Small random delay otherwise
1261 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1264 // Send move ("newmove" event) to people in the room (if our turn)
1265 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1267 move: filtered_move,
1268 index: origMovescount,
1269 // color is required to check if this is my move (if several tabs opened)
1271 cancelDrawOffer: this.drawOffer == ""
1273 if (this.game.type == "live")
1274 sendMove["clock"] = this.game.clocks[colorIdx];
1275 this.opponentGotMove = false;
1276 this.send("newmove", {data: sendMove});
1277 // If the opponent doesn't reply gotmove soon enough, re-send move:
1278 // Do this at most 2 times, because mpore would mean network issues,
1279 // opponent would then be expected to disconnect/reconnect.
1281 const currentUrl = document.location.href;
1282 this.retrySendmove = setInterval(
1286 this.opponentGotMove ||
1287 document.location.href != currentUrl //page change
1289 clearInterval(this.retrySendmove);
1292 const oppsid = this.getOppsid();
1294 // Opponent is disconnected: he'll ask last state
1295 clearInterval(this.retrySendmove);
1297 this.send("newmove", { data: sendMove, target: oppsid });
1305 // Not my move or I'm an observer: just start other player's clock
1306 this.re_setClocks();
1309 this.game.type == "corr" &&
1310 moveCol == this.game.mycolor &&
1313 let boardDiv = document.querySelector(".game");
1314 const afterSetScore = () => {
1316 if (this.st.settings.gotonext && this.nextIds.length > 0)
1317 this.showNextGame();
1319 // The board might have been hidden:
1320 if (boardDiv.style.visibility == "hidden")
1321 boardDiv.style.visibility = "visible";
1324 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1325 // We may play several moves in a row: in case of, remove listener:
1326 let elClone = el.cloneNode(true);
1327 el.parentNode.replaceChild(elClone, el);
1328 elClone.addEventListener(
1331 document.getElementById("modalConfirm").checked = false;
1332 if (!!data.score && data.score != "*")
1334 this.gameOver(data.score, null, afterSetScore);
1335 else afterSetScore();
1338 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1339 V.PlayOnBoard(this.vr.board, move);
1340 const position = this.vr.getBaseFen();
1341 V.UndoOnBoard(this.vr.board, move);
1342 if (["all","byrow"].includes(V.ShowMoves)) {
1343 this.curDiag = getDiagram({
1345 orientation: V.CanFlip ? this.game.mycolor : "w"
1347 document.querySelector("#confirmDiv > .card").style.width =
1348 boardDiv.offsetWidth + "px";
1350 // Incomplete information: just ask confirmation
1351 // Hide the board, because otherwise it could reveal infos
1352 boardDiv.style.visibility = "hidden";
1353 this.moveNotation = getFullNotation(move);
1355 document.getElementById("modalConfirm").checked = true;
1359 if (!!data.score && data.score != "*")
1360 this.gameOver(data.score, null, doProcessMove);
1361 else doProcessMove();
1364 cancelMove: function() {
1365 let boardDiv = document.querySelector(".game");
1366 if (boardDiv.style.visibility == "hidden")
1367 boardDiv.style.visibility = "visible";
1368 document.getElementById("modalConfirm").checked = false;
1369 this.$refs["basegame"].cancelLastMove();
1371 // In corr games, callback to change page only after score is set:
1372 gameOver: function(score, scoreMsg, callback) {
1373 this.game.score = score;
1374 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1375 this.game.scoreMsg = scoreMsg;
1376 this.$set(this.game, "scoreMsg", scoreMsg);
1377 const myIdx = this.game.players.findIndex(p => {
1378 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1381 // OK, I play in this game
1386 if (this.game.type == "live") {
1387 GameStorage.update(this.gameRef.id, scoreObj);
1388 if (!!callback) callback();
1390 else this.updateCorrGame(scoreObj, callback);
1391 // Notify the score to main Hall. TODO: only one player (currently double send)
1392 this.send("result", { gid: this.game.id, score: score });
1393 // Also to MyGames page (TODO: doubled as well...)
1397 gid: this.gameRef.id,
1402 else if (!!callback) callback();
1408 <style lang="sass" scoped>
1414 background-color: lightgreen
1426 @media screen and (min-width: 768px)
1429 @media screen and (max-width: 767px)
1434 display: inline-block
1438 display: inline-block
1440 display: inline-flex
1444 @media screen and (max-width: 767px)
1447 @media screen and (max-width: 767px)
1450 @media screen and (min-width: 768px)
1462 background-color: #edda99
1464 display: inline-block
1473 display: inline-block
1486 animation: blink-animation 2s steps(3, start) infinite
1487 @keyframes blink-animation
1492 display: inline-block
1504 .draw-sent, .draw-sent:hover
1505 background-color: lightyellow
1507 .draw-received, .draw-received:hover
1508 background-color: lightgreen
1510 .draw-threerep, .draw-threerep:hover
1511 background-color: #e4d1fc
1513 .rematch-sent, .rematch-sent:hover
1514 background-color: lightyellow
1516 .rematch-received, .rematch-received:hover
1517 background-color: lightgreen
1520 background-color: #c5fefe
1533 background-color: lightgreen
1535 background-color: red