3 input#modalInfo.modal(type="checkbox")
6 data-checkbox="modalInfo"
9 label.modal-close(for="modalInfo")
11 :href="'#/game/' + rematchId"
12 onClick="document.getElementById('modalInfo').checked=false"
14 | {{ st.tr["Rematch in progress"] }}
15 input#modalChat.modal(
21 data-checkbox="modalChat"
24 label.modal-close(for="modalChat")
26 span {{ st.tr["Participant(s):"] }}
28 v-for="p in Object.values(people)"
29 v-if="p.focus && !!p.name"
33 v-if="Object.values(people).some(p => p.focus && !p.name)"
38 :players="game.players"
39 :pastChats="game.chats"
41 @chatcleared="clearChat"
43 input#modalConfirm.modal(type="checkbox")
44 div#confirmDiv(role="dialog")
47 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
51 span {{ st.tr["Move played:"] + " " }}
52 span.bold {{ moveNotation }}
54 span {{ st.tr["Are you sure?"] }}
55 .button-group#buttonsConfirm
56 // onClick for acceptBtn: set dynamically
58 span {{ st.tr["Validate"] }}
59 button.refuseBtn(@click="cancelMove()")
60 span {{ st.tr["Cancel"] }}
62 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
63 span.variant-cadence {{ game.cadence }}
64 span.variant-name {{ game.vname }}
66 v-if="nextIds.length > 0"
67 @click="showNextGame()"
69 | {{ st.tr["Next_g"] }}
70 button#chatBtn.tooltip(
71 onClick="window.doClick('modalChat')"
74 img(src="/images/icons/chat.svg")
75 #actions(v-if="game.score=='*'")
78 :class="{['draw-' + drawOffer]: true}"
79 :aria-label="st.tr['Draw']"
81 img(src="/images/icons/draw.svg")
85 :aria-label="st.tr['Abort']"
87 img(src="/images/icons/abort.svg")
91 :aria-label="st.tr['Resign']"
93 img(src="/images/icons/resign.svg")
96 @click="clickRematch()"
97 :class="{['rematch-' + rematchOffer]: true}"
98 :aria-label="st.tr['Rematch']"
100 img(src="/images/icons/rematch.svg")
103 span.name(:class="{connected: isConnected(0)}")
104 | {{ game.players[0].name || "@nonymous" }}
106 v-if="game.score=='*'"
107 :class="{yourturn: !!vr && vr.turn == 'w'}"
109 span.time-left {{ virtualClocks[0][0] }}
110 span.time-separator(v-if="!!virtualClocks[0][1]") :
111 span.time-right(v-if="!!virtualClocks[0][1]")
112 | {{ virtualClocks[0][1] }}
114 span.name(:class="{connected: isConnected(1)}")
115 | {{ game.players[1].name || "@nonymous" }}
117 v-if="game.score=='*'"
118 :class="{yourturn: !!vr && vr.turn == 'b'}"
120 span.time-left {{ virtualClocks[1][0] }}
121 span.time-separator(v-if="!!virtualClocks[1][1]") :
122 span.time-right(v-if="!!virtualClocks[1][1]")
123 | {{ virtualClocks[1][1] }}
127 @newmove="processMove"
132 import BaseGame from "@/components/BaseGame.vue";
133 import Chat from "@/components/Chat.vue";
134 import { store } from "@/store";
135 import { GameStorage } from "@/utils/gameStorage";
136 import { ppt } from "@/utils/datetime";
137 import { ajax } from "@/utils/ajax";
138 import { extractTime } from "@/utils/timeControl";
139 import { getRandString } from "@/utils/alea";
140 import { getScoreMessage } from "@/utils/scoring";
141 import { getFullNotation } from "@/utils/notation";
142 import { getDiagram } from "@/utils/printDiagram";
143 import { processModalClick } from "@/utils/modalClick";
144 import { playMove, getFilteredMove } from "@/utils/playUndo";
145 import { ArrayFun } from "@/utils/array";
146 import params from "@/parameters";
156 // gameRef can point to a corr game, local game or remote live game
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
172 roomInitialized: false,
173 // If newmove has wrong index: ask fullgame again:
175 gameIsLoading: false,
176 // If asklastate got no reply, ask again:
178 gotMoveIdx: -1, //last move index received
179 // If newmove got no pingback, send again:
180 opponentGotMove: false,
182 // Incomplete info games: show move played
184 // Intervals from setInterval():
188 // Related to (killing of) self multi-connects:
194 $route: function(to, from) {
195 if (from.params["id"] != to.params["id"]) {
196 // Change everything:
197 this.cleanBeforeDestroy();
198 let boardDiv = document.querySelector(".game");
200 // In case of incomplete information variant:
201 boardDiv.style.visibility = "hidden";
205 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
208 // NOTE: some redundant code with Hall.vue (mostly related to people array)
209 created: function() {
212 mounted: function() {
213 document.addEventListener('visibilitychange', this.visibilityChange);
214 ["chatWrap", "infoDiv"].forEach(eltName => {
215 document.getElementById(eltName)
216 .addEventListener("click", processModalClick);
218 if ("ontouchstart" in window) {
219 // Disable tooltips on smartphones:
220 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
221 elt.classList.remove("tooltip");
225 beforeDestroy: function() {
226 document.removeEventListener('visibilitychange', this.visibilityChange);
227 this.cleanBeforeDestroy();
230 visibilityChange: function() {
231 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
233 document.visibilityState == "visible"
238 atCreation: function() {
239 // 0] (Re)Set variables
240 this.gameRef = this.$route.params["id"];
241 // next = next corr games IDs to navigate faster (if applicable)
242 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
243 // Always add myself to players' list
244 const my = this.st.user;
255 players: [{ name: "" }, { name: "" }],
259 let chatComp = this.$refs["chatcomp"];
260 if (!!chatComp) chatComp.chats = [];
261 this.virtualClocks = [[0,0], [0,0]];
264 this.lastateAsked = false;
265 this.rematchOffer = "";
266 this.lastate = undefined;
267 this.roomInitialized = false;
268 this.askGameTime = 0;
269 this.gameIsLoading = false;
270 this.gotLastate = false;
271 this.gotMoveIdx = -1;
272 this.opponentGotMove = false;
273 this.askLastate = null;
274 this.retrySendmove = null;
275 this.clockUpdate = null;
276 this.newConnect = {};
278 // 1] Initialize connection
279 this.connexionString =
288 // Discard potential "/?next=[...]" for page indication:
289 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
290 this.conn = new WebSocket(this.connexionString);
291 this.conn.onmessage = this.socketMessageListener;
292 this.conn.onclose = this.socketCloseListener;
293 // Socket init required before loading remote game:
294 const socketInit = callback => {
295 if (!!this.conn && this.conn.readyState == 1)
299 // Socket not ready yet (initial loading)
300 // NOTE: first arg is Websocket object, unused here:
301 this.conn.onopen = () => callback();
303 this.fetchGame((game) => {
305 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
307 // Live game stored remotely: need socket to retrieve it
308 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
309 // --> It will be given when receiving "fullgame" socket event.
310 socketInit(() => { this.send("askfullgame"); });
313 cleanBeforeDestroy: function() {
314 if (!!this.askLastate)
315 clearInterval(this.askLastate);
316 if (!!this.retrySendmove)
317 clearInterval(this.retrySendmove);
318 if (!!this.clockUpdate)
319 clearInterval(this.clockUpdate);
320 this.send("disconnect");
322 roomInit: function() {
323 if (!this.roomInitialized) {
324 // Notify the room only now that I connected, because
325 // messages might be lost otherwise (if game loading is slow)
326 this.send("connect");
327 this.send("pollclients");
328 // We may ask fullgame several times if some moves are lost,
329 // but room should be init only once:
330 this.roomInitialized = true;
333 send: function(code, obj) {
335 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
337 isConnected: function(index) {
338 const player = this.game.players[index];
339 // Is it me ? In this case no need to bother with focus
340 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
341 // Still have to check for name (because of potential multi-accounts
342 // on same browser, although this should be rare...)
343 return (!this.st.user.name || this.st.user.name == player.name);
344 // Try to find a match in people:
348 Object.keys(this.people).some(sid =>
349 sid == player.sid && this.people[sid].focus)
354 Object.values(this.people).some(p =>
355 p.id == player.id && p.focus)
359 getOppsid: function() {
360 let oppsid = this.game.oppsid;
362 oppsid = Object.keys(this.people).find(
363 sid => this.people[sid].id == this.game.oppid
366 // oppsid is useful only if opponent is online:
367 if (!!oppsid && !!this.people[oppsid]) return oppsid;
370 toggleChat: function() {
371 if (document.getElementById("modalChat").checked)
373 document.getElementById("inputChat").focus();
374 // TODO: next line is only required when exiting chat,
375 // but the event for now isn't well detected.
376 document.getElementById("chatBtn").classList.remove("somethingnew");
378 processChat: function(chat) {
379 this.send("newchat", { data: chat });
380 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
381 if (this.game.type == "corr" && this.st.user.id > 0)
382 this.updateCorrGame({ chat: chat });
384 clearChat: function() {
385 // Nothing more to do if game is live (chats not recorded)
386 if (this.game.type == "corr") {
387 if (!!this.game.mycolor) {
391 { data: { gid: this.game.id } }
394 this.$set(this.game, "chats", []);
397 getGameType: function(game) {
398 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
400 // Notify something after a new move (to opponent and me on MyGames page)
401 notifyMyGames: function(thing, data) {
406 targets: this.game.players.map(p => {
407 return { sid: p.sid, id: p.id };
412 showNextGame: function() {
413 // Did I play in current game? If not, add it to nextIds list
414 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
415 this.nextIds.unshift(this.game.id);
416 const nextGid = this.nextIds.pop();
418 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
420 askGameAgain: function() {
421 this.gameIsLoading = true;
422 const currentUrl = document.location.href;
423 const doAskGame = () => {
424 if (document.location.href != currentUrl) return; //page change
425 this.fetchGame((game) => {
427 // This is my game: just reload.
430 // Just ask fullgame again (once!), this is much simpler.
431 // If this fails, the user could just reload page :/
432 this.send("askfullgame");
435 // Delay of at least 2s between two game requests
436 const now = Date.now();
437 const delay = Math.max(2000 - (now - this.askGameTime), 0);
438 this.askGameTime = now;
439 setTimeout(doAskGame, delay);
441 socketMessageListener: function(msg) {
442 if (!this.conn) return;
443 const data = JSON.parse(msg.data);
446 // TODO: shuffling and random filtering on server, if
447 // the room is really crowded.
448 data.sockIds.forEach(sid => {
449 if (sid != this.st.user.sid) {
450 this.people[sid] = { focus: true };
451 this.send("askidentity", { target: sid });
456 if (!this.people[data.from]) {
457 this.people[data.from] = { focus: true };
458 this.newConnect[data.from] = true; //for self multi-connects tests
459 this.send("askidentity", { target: data.from });
463 this.$delete(this.people, data.from);
466 let player = this.people[data.from];
469 this.$forceUpdate(); //TODO: shouldn't be required
474 let player = this.people[data.from];
476 player.focus = false;
477 this.$forceUpdate(); //TODO: shouldn't be required
482 // I logged in elsewhere:
484 alert(this.st.tr["New connexion detected: tab now offline"]);
486 case "askidentity": {
487 // Request for identification
489 // Decompose to avoid revealing email
490 name: this.st.user.name,
491 sid: this.st.user.sid,
494 this.send("identity", { data: me, target: data.from });
498 const user = data.data;
499 let player = this.people[user.sid];
500 // player.focus is already set
501 player.name = user.name;
503 this.$forceUpdate(); //TODO: shouldn't be required
504 // If I multi-connect, kill current connexion if no mark (I'm older)
505 if (this.newConnect[user.sid]) {
508 user.id == this.st.user.id &&
509 user.sid != this.st.user.sid &&
510 !this.killed[this.st.user.sid]
512 this.send("killme", { sid: this.st.user.sid });
513 this.killed[this.st.user.sid] = true;
515 delete this.newConnect[user.sid];
517 if (!this.killed[this.st.user.sid]) {
518 // Ask potentially missed last state, if opponent and I play
520 !!this.game.mycolor &&
521 this.game.type == "live" &&
522 this.game.score == "*" &&
523 this.game.players.some(p => p.sid == user.sid)
525 this.send("asklastate", { target: user.sid });
527 this.askLastate = setInterval(
529 // Ask at most 3 times:
530 // if no reply after that there should be a network issue.
534 !!this.people[user.sid]
536 this.send("asklastate", { target: user.sid });
539 clearInterval(this.askLastate);
549 // Send current (live) game if not asked by any of the players
551 this.game.type == "live" &&
552 this.game.players.every(p => p.sid != data.from[0])
557 players: this.game.players,
559 cadence: this.game.cadence,
560 score: this.game.score
562 this.send("game", { data: myGame, target: data.from });
566 const gameToSend = Object.keys(this.game)
569 "id","fen","players","vid","cadence","fenStart","vname",
570 "moves","clocks","initime","score","drawOffer","rematchOffer"
574 obj[k] = this.game[k];
579 this.send("fullgame", { data: gameToSend, target: data.from });
582 // Callback "roomInit" to poll clients only after game is loaded
583 this.loadVariantThenGame(data.data, this.roomInit);
586 // Sending informative last state if I played a move or score != "*"
587 // If the game or moves aren't loaded yet, delay the sending:
588 if (!this.game || !this.game.moves) this.lastateAsked = true;
589 else this.sendLastate(data.from);
592 // Got opponent infos about last move
593 this.gotLastate = true;
594 if (!data.data.nothing) {
595 this.lastate = data.data;
596 if (this.game.rendered)
597 // Game is rendered (Board component)
598 this.processLastate();
599 // Else: will be processed when game is ready
604 const movePlus = data.data;
605 const movesCount = this.game.moves.length;
606 if (movePlus.index > movesCount) {
607 // This can only happen if I'm an observer and missed a move.
608 if (this.gotMoveIdx < movePlus.index)
609 this.gotMoveIdx = movePlus.index;
610 if (!this.gameIsLoading) this.askGameAgain();
614 movePlus.index < movesCount ||
615 this.gotMoveIdx >= movePlus.index
617 // Opponent re-send but we already have the move:
618 // (maybe he didn't receive our pingback...)
619 this.send("gotmove", {data: movePlus.index, target: data.from});
621 this.gotMoveIdx = movePlus.index;
622 const receiveMyMove = (movePlus.color == this.game.mycolor);
623 if (!receiveMyMove && !!this.game.mycolor)
624 // Notify opponent that I got the move:
625 this.send("gotmove", {data: movePlus.index, target: data.from});
626 if (movePlus.cancelDrawOffer) {
627 // Opponent refuses draw
629 // NOTE for corr games: drawOffer reset by player in turn
631 this.game.type == "live" &&
632 !!this.game.mycolor &&
635 GameStorage.update(this.gameRef, { drawOffer: "" });
638 this.$refs["basegame"].play(movePlus.move, "received", null, true);
642 clock: movePlus.clock,
643 receiveMyMove: receiveMyMove
651 this.opponentGotMove = true;
652 // Now his clock starts running:
653 const oppIdx = ['w','b'].indexOf(this.vr.turn);
654 this.game.initime[oppIdx] = Date.now();
659 const score = (data.data == "b" ? "1-0" : "0-1");
660 const side = (data.data == "w" ? "White" : "Black");
661 this.gameOver(score, side + " surrender");
664 this.gameOver("?", "Stop");
667 this.gameOver("1/2", data.data);
670 // NOTE: observers don't know who offered draw
671 this.drawOffer = "received";
672 if (this.game.type == "live") {
675 { drawOffer: V.GetOppCol(this.game.mycolor) }
680 // NOTE: observers don't know who offered rematch
681 this.rematchOffer = data.data ? "received" : "";
682 if (this.game.type == "live") {
685 { rematchOffer: V.GetOppCol(this.game.mycolor) }
690 // A game started, redirect if I'm playing in
691 const gameInfo = data.data;
692 const gameType = this.getGameType(gameInfo);
694 gameType == "live" &&
695 gameInfo.players.some(p => p.sid == this.st.user.sid)
697 this.addAndGotoLiveGame(gameInfo);
699 gameType == "corr" &&
700 gameInfo.players.some(p => p.id == this.st.user.id)
702 this.$router.push("/game/" + gameInfo.id);
704 this.rematchId = gameInfo.id;
705 document.getElementById("modalInfo").checked = true;
710 this.$refs["chatcomp"].newChat(data.data);
711 if (!document.getElementById("modalChat").checked)
712 document.getElementById("chatBtn").classList.add("somethingnew");
716 socketCloseListener: function() {
717 this.conn = new WebSocket(this.connexionString);
718 this.conn.addEventListener("message", this.socketMessageListener);
719 this.conn.addEventListener("close", this.socketCloseListener);
721 updateCorrGame: function(obj, callback) {
731 if (!!callback) callback();
736 sendLastate: function(target) {
738 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
739 this.game.score != "*" ||
740 this.drawOffer == "sent" ||
741 this.rematchOffer == "sent"
743 // Send our "last state" informations to opponent
744 const L = this.game.moves.length;
745 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
747 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
748 clock: this.game.clocks[myIdx],
749 // Since we played a move (or abort or resign),
750 // only drawOffer=="sent" is possible
751 drawSent: this.drawOffer == "sent",
752 rematchSent: this.rematchOffer == "sent",
753 score: this.game.score,
754 scoreMsg: this.game.scoreMsg,
756 initime: this.game.initime[1 - myIdx] //relevant only if I played
758 this.send("lastate", { data: myLastate, target: target });
760 this.send("lastate", { data: {nothing: true}, target: target });
763 // lastate was received, but maybe game wasn't ready yet:
764 processLastate: function() {
765 const data = this.lastate;
766 this.lastate = undefined; //security...
767 const L = this.game.moves.length;
768 if (data.movesCount > L) {
769 // Just got last move from him
770 this.$refs["basegame"].play(data.lastMove, "received", null, true);
771 this.processMove(data.lastMove, { clock: data.clock });
773 if (data.drawSent) this.drawOffer = "received";
774 if (data.rematchSent) this.rematchOffer = "received";
775 if (data.score != "*") {
777 if (this.game.score == "*")
778 this.gameOver(data.score, data.scoreMsg);
781 clickDraw: function() {
782 if (!this.game.mycolor) return; //I'm just spectator
783 if (["received", "threerep"].includes(this.drawOffer)) {
784 if (!confirm(this.st.tr["Accept draw?"])) return;
786 this.drawOffer == "received"
788 : "Three repetitions";
789 this.send("draw", { data: message });
790 this.gameOver("1/2", message);
791 } else if (this.drawOffer == "") {
792 // No effect if drawOffer == "sent"
793 if (this.game.mycolor != this.vr.turn) {
794 alert(this.st.tr["Draw offer only in your turn"]);
797 if (!confirm(this.st.tr["Offer draw?"])) return;
798 this.drawOffer = "sent";
799 this.send("drawoffer");
800 if (this.game.type == "live") {
803 { drawOffer: this.game.mycolor }
805 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
808 addAndGotoLiveGame: function(gameInfo, callback) {
809 const game = Object.assign(
813 // (other) Game infos: constant
814 fenStart: gameInfo.fen,
815 vname: this.game.vname,
817 // Game state (including FEN): will be updated
819 clocks: [-1, -1], //-1 = unstarted
820 initime: [0, 0], //initialized later
824 GameStorage.add(game, (err) => {
825 // No error expected.
827 if (this.st.settings.sound)
828 new Audio("/sounds/newgame.flac").play().catch(() => {});
829 if (!!callback) callback();
830 this.$router.push("/game/" + gameInfo.id);
834 clickRematch: function() {
835 if (!this.game.mycolor) return; //I'm just spectator
836 if (this.rematchOffer == "received") {
839 id: getRandString(), //ignored if corr
840 fen: V.GenRandInitFen(this.game.randomness),
841 players: this.game.players.reverse(),
843 cadence: this.game.cadence
845 const notifyNewGame = () => {
846 const oppsid = this.getOppsid(); //may be null
847 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
848 // To main Hall if corr game:
849 if (this.game.type == "corr")
850 this.send("newgame", { data: gameInfo });
851 // Also to MyGames page:
852 this.notifyMyGames("newgame", gameInfo);
854 if (this.game.type == "live")
855 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
862 // cid is useful to delete the challenge:
863 data: { gameInfo: gameInfo },
864 success: (response) => {
865 gameInfo.id = response.gameId;
867 this.$router.push("/game/" + response.gameId);
872 } else if (this.rematchOffer == "") {
873 this.rematchOffer = "sent";
874 this.send("rematchoffer", { data: true });
875 if (this.game.type == "live") {
878 { rematchOffer: this.game.mycolor }
880 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
881 } else if (this.rematchOffer == "sent") {
882 // Toggle rematch offer (on --> off)
883 this.rematchOffer = "";
884 this.send("rematchoffer", { data: false });
885 if (this.game.type == "live") {
890 } else this.updateCorrGame({ rematchOffer: 'n' });
893 abortGame: function() {
894 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
895 this.gameOver("?", "Stop");
899 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
901 this.send("resign", { data: this.game.mycolor });
902 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
903 const side = (this.game.mycolor == "w" ? "White" : "Black");
904 this.gameOver(score, side + " surrender");
906 loadGame: function(game, callback) {
907 this.vr = new V(game.fen);
908 const gtype = this.getGameType(game);
909 const tc = extractTime(game.cadence);
910 const myIdx = game.players.findIndex(p => {
911 return p.sid == this.st.user.sid || p.id == this.st.user.id;
913 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
914 if (!game.chats) game.chats = []; //live games don't have chat history
915 if (gtype == "corr") {
916 // NOTE: clocks in seconds, initime in milliseconds
917 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
918 game.clocks = [tc.mainTime, tc.mainTime];
919 const L = game.moves.length;
920 if (game.score == "*") {
921 // Set clocks + initime
922 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
923 if (L >= 1) game.initime[L % 2] = game.moves[L-1].played;
924 // NOTE: game.clocks shouldn't be computed right now:
925 // job will be done in re_setClocks() called soon below.
927 // Sort chat messages from newest to oldest
928 game.chats.sort((c1, c2) => {
929 return c2.added - c1.added;
931 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
932 // Did a chat message arrive after my last move?
934 if (L == 1 && myIdx == 0)
935 dtLastMove = game.moves[0].played;
938 // It's now white turn
939 dtLastMove = game.moves[L-1-(1-myIdx)].played;
942 dtLastMove = game.moves[L-1-myIdx].played;
945 if (dtLastMove < game.chats[0].added)
946 document.getElementById("chatBtn").classList.add("somethingnew");
948 // Now that we used idx and played, re-format moves as for live games
949 game.moves = game.moves.map(m => m.squares);
951 if (gtype == "live" && game.clocks[0] < 0) {
952 // Game is unstarted. clocks and initime are ignored until move 2
953 game.clocks = [tc.mainTime, tc.mainTime];
954 game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER];
956 // I play in this live game
957 GameStorage.update(game.id, {
959 initime: game.initime
963 // TODO: merge next 2 "if" conditions
964 if (!!game.drawOffer) {
965 if (game.drawOffer == "t")
967 this.drawOffer = "threerep";
969 // Draw offered by any of the players:
970 if (myIdx < 0) this.drawOffer = "received";
972 // I play in this game:
974 (game.drawOffer == "w" && myIdx == 0) ||
975 (game.drawOffer == "b" && myIdx == 1)
977 this.drawOffer = "sent";
978 else this.drawOffer = "received";
982 if (!!game.rematchOffer) {
983 if (myIdx < 0) this.rematchOffer = "received";
985 // I play in this game:
987 (game.rematchOffer == "w" && myIdx == 0) ||
988 (game.rematchOffer == "b" && myIdx == 1)
990 this.rematchOffer = "sent";
991 else this.rematchOffer = "received";
994 this.repeat = {}; //reset: scan past moves' FEN:
996 let vr_tmp = new V(game.fenStart);
998 game.moves.forEach(m => {
1000 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1001 this.repeat[fenIdx] = this.repeat[fenIdx]
1002 ? this.repeat[fenIdx] + 1
1005 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1006 this.game = Object.assign(
1007 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1010 increment: tc.increment,
1012 // opponent sid not strictly required (or available), but easier
1013 // at least oppsid or oppid is available anyway:
1014 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1015 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1019 this.$refs["basegame"].re_setVariables(this.game);
1020 if (!this.gameIsLoading) {
1022 this.gotMoveIdx = game.moves.length - 1;
1023 // If we arrive here after 'nextGame' action, the board might be hidden
1024 let boardDiv = document.querySelector(".game");
1025 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1026 boardDiv.style.visibility = "visible";
1028 this.re_setClocks();
1029 this.$nextTick(() => {
1030 this.game.rendered = true;
1031 // Did lastate arrive before game was rendered?
1032 if (this.lastate) this.processLastate();
1034 if (this.lastateAsked) {
1035 this.lastateAsked = false;
1036 this.sendLastate(game.oppsid);
1038 if (this.gameIsLoading) {
1039 this.gameIsLoading = false;
1040 if (this.gotMoveIdx >= game.moves.length)
1041 // Some moves arrived meanwhile...
1042 this.askGameAgain();
1044 if (!!callback) callback();
1046 loadVariantThenGame: async function(game, callback) {
1047 await import("@/variants/" + game.vname + ".js")
1048 .then((vModule) => {
1049 window.V = vModule[game.vname + "Rules"];
1050 this.loadGame(game, callback);
1053 // 3 cases for loading a game:
1054 // - from indexedDB (running or completed live game I play)
1055 // - from server (one correspondance game I play[ed] or not)
1056 // - from remote peer (one live game I don't play, finished or not)
1057 fetchGame: function(callback) {
1058 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1059 // corr games identifiers are integers
1064 data: { gid: this.gameRef },
1066 res.game.moves.forEach(m => {
1067 m.squares = JSON.parse(m.squares);
1074 // Local game (or live remote)
1075 GameStorage.get(this.gameRef, callback);
1077 re_setClocks: function() {
1078 if (this.game.moves.length < 2 || this.game.score != "*") {
1079 // 1st move not completed yet, or game over: freeze time
1080 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1083 const currentTurn = this.vr.turn;
1084 const currentMovesCount = this.game.moves.length;
1085 const colorIdx = ["w", "b"].indexOf(currentTurn);
1087 this.game.clocks[colorIdx] -
1088 (Date.now() - this.game.initime[colorIdx]) / 1000;
1089 this.virtualClocks = [0, 1].map(i => {
1091 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
1092 return ppt(this.game.clocks[i] - removeTime).split(':');
1094 this.clockUpdate = setInterval(
1098 this.game.moves.length > currentMovesCount ||
1099 this.game.score != "*"
1101 clearInterval(this.clockUpdate);
1104 currentTurn == "w" ? "0-1" : "1-0",
1111 ppt(Math.max(0, --countdown)).split(':')
1117 // Update variables and storage after a move:
1118 processMove: function(move, data) {
1119 if (!data) data = {};
1120 const moveCol = this.vr.turn;
1121 const colorIdx = ["w", "b"].indexOf(moveCol);
1122 const nextIdx = 1 - colorIdx;
1123 const doProcessMove = () => {
1124 const origMovescount = this.game.moves.length;
1125 let addTime = 0; //for live games
1126 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1127 if (this.drawOffer == "received")
1129 this.drawOffer = "";
1130 if (this.game.type == "live" && origMovescount >= 2) {
1131 const elapsed = Date.now() - this.game.initime[colorIdx];
1132 // elapsed time is measured in milliseconds
1133 addTime = this.game.increment - elapsed / 1000;
1136 // Update current game object:
1137 playMove(move, this.vr);
1138 // The move is played: stop clock
1139 clearInterval(this.clockUpdate);
1141 // Received move, score is computed in BaseGame, but maybe not yet.
1142 // ==> Compute it here, although this is redundant (TODO)
1143 data.score = this.vr.getCurrentScore();
1144 if (data.score != "*") this.gameOver(data.score);
1145 this.game.moves.push(move);
1146 this.game.fen = this.vr.getFen();
1147 if (this.game.type == "live") {
1148 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
1149 else this.game.clocks[colorIdx] += addTime;
1151 // In corr games, just reset clock to mainTime:
1152 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1154 // NOTE: opponent's initime is reset after "gotmove" is received
1156 !this.game.mycolor ||
1157 moveCol != this.game.mycolor ||
1158 !!data.receiveMyMove
1160 this.game.initime[nextIdx] = Date.now();
1162 // If repetition detected, consider that a draw offer was received:
1163 const fenObj = this.vr.getFenForRepeat();
1164 this.repeat[fenObj] =
1165 !!this.repeat[fenObj]
1166 ? this.repeat[fenObj] + 1
1168 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1169 else if (this.drawOffer == "threerep") this.drawOffer = "";
1170 if (!!this.game.mycolor && !data.receiveMyMove) {
1171 // NOTE: 'var' to see that variable outside this block
1172 var filtered_move = getFilteredMove(move);
1174 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1175 // Notify turn on MyGames page:
1184 // Since corr games are stored at only one location, update should be
1185 // done only by one player for each move:
1187 !!this.game.mycolor &&
1188 !data.receiveMyMove &&
1189 (this.game.type == "live" || moveCol == this.game.mycolor)
1192 switch (this.drawOffer) {
1197 drawCode = this.game.mycolor;
1200 drawCode = V.GetOppCol(this.game.mycolor);
1203 if (this.game.type == "corr") {
1204 // corr: only move, fen and score
1205 this.updateCorrGame({
1208 squares: filtered_move,
1211 // Code "n" for "None" to force reset (otherwise it's ignored)
1212 drawOffer: drawCode || "n"
1216 const updateStorage = () => {
1217 GameStorage.update(this.gameRef, {
1219 move: filtered_move,
1220 moveIdx: origMovescount,
1221 clocks: this.game.clocks,
1222 initime: this.game.initime,
1226 // The active tab can update storage immediately
1227 if (!document.hidden) updateStorage();
1228 // Small random delay otherwise
1229 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1232 // Send move ("newmove" event) to people in the room (if our turn)
1233 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1235 move: filtered_move,
1236 index: origMovescount,
1237 // color is required to check if this is my move (if several tabs opened)
1239 cancelDrawOffer: this.drawOffer == ""
1241 if (this.game.type == "live")
1242 sendMove["clock"] = this.game.clocks[colorIdx];
1243 // (Live) Clocks will re-start when the opponent pingback arrive
1244 this.opponentGotMove = false;
1245 this.send("newmove", {data: sendMove});
1246 // If the opponent doesn't reply gotmove soon enough, re-send move:
1247 // Do this at most 2 times, because mpore would mean network issues,
1248 // opponent would then be expected to disconnect/reconnect.
1250 const currentUrl = document.location.href;
1251 this.retrySendmove = setInterval(
1255 this.opponentGotMove ||
1256 document.location.href != currentUrl //page change
1258 clearInterval(this.retrySendmove);
1261 const oppsid = this.getOppsid();
1263 // Opponent is disconnected: he'll ask last state
1264 clearInterval(this.retrySendmove);
1266 this.send("newmove", { data: sendMove, target: oppsid });
1274 // Not my move or I'm an observer: just start other player's clock
1275 this.re_setClocks();
1278 this.game.type == "corr" &&
1279 moveCol == this.game.mycolor &&
1282 let boardDiv = document.querySelector(".game");
1283 const afterSetScore = () => {
1285 if (this.st.settings.gotonext && this.nextIds.length > 0)
1286 this.showNextGame();
1288 // The board might have been hidden:
1289 if (boardDiv.style.visibility == "hidden")
1290 boardDiv.style.visibility = "visible";
1291 if (data.score == "*") {
1292 this.game.initime[nextIdx] = Date.now();
1293 this.re_setClocks();
1297 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1298 // We may play several moves in a row: in case of, remove listener:
1299 let elClone = el.cloneNode(true);
1300 el.parentNode.replaceChild(elClone, el);
1301 elClone.addEventListener(
1304 document.getElementById("modalConfirm").checked = false;
1305 if (!!data.score && data.score != "*")
1307 this.gameOver(data.score, null, afterSetScore);
1308 else afterSetScore();
1311 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1312 V.PlayOnBoard(this.vr.board, move);
1313 const position = this.vr.getBaseFen();
1314 V.UndoOnBoard(this.vr.board, move);
1315 if (["all","byrow"].includes(V.ShowMoves)) {
1316 this.curDiag = getDiagram({
1318 orientation: V.CanFlip ? this.game.mycolor : "w"
1320 document.querySelector("#confirmDiv > .card").style.width =
1321 boardDiv.offsetWidth + "px";
1323 // Incomplete information: just ask confirmation
1324 // Hide the board, because otherwise it could reveal infos
1325 boardDiv.style.visibility = "hidden";
1326 this.moveNotation = getFullNotation(move);
1328 document.getElementById("modalConfirm").checked = true;
1332 if (!!data.score && data.score != "*")
1333 this.gameOver(data.score, null, doProcessMove);
1334 else doProcessMove();
1337 cancelMove: function() {
1338 let boardDiv = document.querySelector(".game");
1339 if (boardDiv.style.visibility == "hidden")
1340 boardDiv.style.visibility = "visible";
1341 document.getElementById("modalConfirm").checked = false;
1342 this.$refs["basegame"].cancelLastMove();
1344 // In corr games, callback to change page only after score is set:
1345 gameOver: function(score, scoreMsg, callback) {
1346 this.game.score = score;
1347 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1348 this.game.scoreMsg = scoreMsg;
1349 this.$set(this.game, "scoreMsg", scoreMsg);
1350 const myIdx = this.game.players.findIndex(p => {
1351 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1354 // OK, I play in this game
1359 if (this.game.type == "live") {
1360 GameStorage.update(this.gameRef, scoreObj);
1361 if (!!callback) callback();
1363 else this.updateCorrGame(scoreObj, callback);
1364 // Notify the score to main Hall. TODO: only one player (currently double send)
1365 this.send("result", { gid: this.game.id, score: score });
1366 // Also to MyGames page (TODO: doubled as well...)
1375 else if (!!callback) callback();
1381 <style lang="sass" scoped>
1387 background-color: lightgreen
1399 @media screen and (min-width: 768px)
1402 @media screen and (max-width: 767px)
1407 display: inline-block
1411 display: inline-block
1413 display: inline-flex
1417 @media screen and (max-width: 767px)
1420 @media screen and (max-width: 767px)
1423 @media screen and (min-width: 768px)
1435 background-color: #edda99
1437 display: inline-block
1446 display: inline-block
1459 animation: blink-animation 2s steps(3, start) infinite
1460 @keyframes blink-animation
1465 display: inline-block
1477 .draw-sent, .draw-sent:hover
1478 background-color: lightyellow
1480 .draw-received, .draw-received:hover
1481 background-color: lightgreen
1483 .draw-threerep, .draw-threerep:hover
1484 background-color: #e4d1fc
1486 .rematch-sent, .rematch-sent:hover
1487 background-color: lightyellow
1489 .rematch-received, .rematch-received:hover
1490 background-color: lightgreen
1493 background-color: #c5fefe
1506 background-color: lightgreen
1508 background-color: red