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 (to.path.length < 6 || to.path.substr(6) != "/game/")
197 this.cleanBeforeDestroy();
198 else if (from.params["id"] != to.params["id"]) {
199 // Change everything:
200 this.cleanBeforeDestroy();
201 let boardDiv = document.querySelector(".game");
203 // In case of incomplete information variant:
204 boardDiv.style.visibility = "hidden";
208 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
211 // NOTE: some redundant code with Hall.vue (mostly related to people array)
212 created: function() {
215 mounted: function() {
216 ["chatWrap", "infoDiv"].forEach(eltName => {
217 document.getElementById(eltName)
218 .addEventListener("click", processModalClick);
220 if ("ontouchstart" in window) {
221 // Disable tooltips on smartphones:
222 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
223 elt.classList.remove("tooltip");
227 beforeDestroy: function() {
228 this.cleanBeforeDestroy();
231 cleanBeforeDestroy: function() {
232 document.removeEventListener('visibilitychange', this.visibilityChange);
233 if (!!this.askLastate)
234 clearInterval(this.askLastate);
235 if (!!this.retrySendmove)
236 clearInterval(this.retrySendmove);
237 if (!!this.clockUpdate)
238 clearInterval(this.clockUpdate);
239 this.conn.removeEventListener("message", this.socketMessageListener);
240 this.conn.removeEventListener("close", this.socketCloseListener);
241 this.send("disconnect");
244 visibilityChange: function() {
245 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
247 document.visibilityState == "visible"
252 atCreation: function() {
253 document.addEventListener('visibilitychange', this.visibilityChange);
254 // 0] (Re)Set variables
255 this.gameRef = this.$route.params["id"];
256 // next = next corr games IDs to navigate faster (if applicable)
257 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
258 // Always add myself to players' list
259 const my = this.st.user;
270 players: [{ name: "" }, { name: "" }],
274 let chatComp = this.$refs["chatcomp"];
275 if (!!chatComp) chatComp.chats = [];
276 this.virtualClocks = [[0,0], [0,0]];
279 this.lastateAsked = false;
280 this.rematchOffer = "";
281 this.lastate = undefined;
282 this.roomInitialized = false;
283 this.askGameTime = 0;
284 this.gameIsLoading = false;
285 this.gotLastate = false;
286 this.gotMoveIdx = -1;
287 this.opponentGotMove = false;
288 this.askLastate = null;
289 this.retrySendmove = null;
290 this.clockUpdate = null;
291 this.newConnect = {};
293 // 1] Initialize connection
294 this.connexionString =
303 // Discard potential "/?next=[...]" for page indication:
304 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
305 this.conn = new WebSocket(this.connexionString);
306 this.conn.addEventListener("message", this.socketMessageListener);
307 this.conn.addEventListener("close", this.socketCloseListener);
308 // Socket init required before loading remote game:
309 const socketInit = callback => {
310 if (this.conn.readyState == 1)
314 // Socket not ready yet (initial loading)
315 // NOTE: first arg is Websocket object, unused here:
316 this.conn.onopen = () => callback();
318 this.fetchGame((game) => {
320 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
322 // Live game stored remotely: need socket to retrieve it
323 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
324 // --> It will be given when receiving "fullgame" socket event.
325 socketInit(() => { this.send("askfullgame"); });
328 roomInit: function() {
329 if (!this.roomInitialized) {
330 // Notify the room only now that I connected, because
331 // messages might be lost otherwise (if game loading is slow)
332 this.send("connect");
333 this.send("pollclients");
334 // We may ask fullgame several times if some moves are lost,
335 // but room should be init only once:
336 this.roomInitialized = true;
339 send: function(code, obj) {
341 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
343 isConnected: function(index) {
344 const player = this.game.players[index];
345 // Is it me ? In this case no need to bother with focus
346 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
347 // Still have to check for name (because of potential multi-accounts
348 // on same browser, although this should be rare...)
349 return (!this.st.user.name || this.st.user.name == player.name);
350 // Try to find a match in people:
354 Object.keys(this.people).some(sid =>
355 sid == player.sid && this.people[sid].focus)
360 Object.values(this.people).some(p =>
361 p.id == player.id && p.focus)
365 getOppsid: function() {
366 let oppsid = this.game.oppsid;
368 oppsid = Object.keys(this.people).find(
369 sid => this.people[sid].id == this.game.oppid
372 // oppsid is useful only if opponent is online:
373 if (!!oppsid && !!this.people[oppsid]) return oppsid;
376 toggleChat: function() {
377 if (document.getElementById("modalChat").checked)
379 document.getElementById("inputChat").focus();
380 // TODO: next line is only required when exiting chat,
381 // but the event for now isn't well detected.
382 document.getElementById("chatBtn").classList.remove("somethingnew");
384 processChat: function(chat) {
385 this.send("newchat", { data: chat });
386 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
387 if (this.game.type == "corr" && this.st.user.id > 0)
388 this.updateCorrGame({ chat: chat });
390 clearChat: function() {
391 // Nothing more to do if game is live (chats not recorded)
392 if (this.game.type == "corr") {
393 if (!!this.game.mycolor) {
397 { data: { gid: this.game.id } }
400 this.$set(this.game, "chats", []);
403 getGameType: function(game) {
404 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
406 // Notify something after a new move (to opponent and me on MyGames page)
407 notifyMyGames: function(thing, data) {
412 targets: this.game.players.map(p => {
413 return { sid: p.sid, id: p.id };
418 showNextGame: function() {
419 // Did I play in current game? If not, add it to nextIds list
420 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
421 this.nextIds.unshift(this.game.id);
422 const nextGid = this.nextIds.pop();
424 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
426 askGameAgain: function() {
427 this.gameIsLoading = true;
428 const currentUrl = document.location.href;
429 const doAskGame = () => {
430 if (document.location.href != currentUrl) return; //page change
431 this.fetchGame((game) => {
433 // This is my game: just reload.
436 // Just ask fullgame again (once!), this is much simpler.
437 // If this fails, the user could just reload page :/
438 this.send("askfullgame");
441 // Delay of at least 2s between two game requests
442 const now = Date.now();
443 const delay = Math.max(2000 - (now - this.askGameTime), 0);
444 this.askGameTime = now;
445 setTimeout(doAskGame, delay);
447 socketMessageListener: function(msg) {
448 if (!this.conn) return;
449 const data = JSON.parse(msg.data);
452 // TODO: shuffling and random filtering on server, if
453 // the room is really crowded.
454 data.sockIds.forEach(sid => {
455 if (sid != this.st.user.sid) {
456 this.people[sid] = { focus: true };
457 this.send("askidentity", { target: sid });
462 if (!this.people[data.from]) {
463 this.people[data.from] = { focus: true };
464 this.newConnect[data.from] = true; //for self multi-connects tests
465 this.send("askidentity", { target: data.from });
466 } else if (!this.people[data.from].focus) {
467 this.people[data.from].focus = true;
468 this.$forceUpdate(); //TODO: shouldn't be required
472 this.$delete(this.people, data.from);
475 let player = this.people[data.from];
478 this.$forceUpdate(); //TODO: shouldn't be required
483 let player = this.people[data.from];
485 player.focus = false;
486 this.$forceUpdate(); //TODO: shouldn't be required
491 // I logged in elsewhere:
492 this.conn.removeEventListener("message", this.socketMessageListener);
493 this.conn.removeEventListener("close", this.socketCloseListener);
495 alert(this.st.tr["New connexion detected: tab now offline"]);
497 case "askidentity": {
498 // Request for identification
500 // Decompose to avoid revealing email
501 name: this.st.user.name,
502 sid: this.st.user.sid,
505 this.send("identity", { data: me, target: data.from });
509 const user = data.data;
510 let player = this.people[user.sid];
511 // player.focus is already set
512 player.name = user.name;
514 this.$forceUpdate(); //TODO: shouldn't be required
515 // If I multi-connect, kill current connexion if no mark (I'm older)
516 if (this.newConnect[user.sid]) {
519 user.id == this.st.user.id &&
520 user.sid != this.st.user.sid &&
521 !this.killed[this.st.user.sid]
523 this.send("killme", { sid: this.st.user.sid });
524 this.killed[this.st.user.sid] = true;
526 delete this.newConnect[user.sid];
528 if (!this.killed[this.st.user.sid]) {
529 // Ask potentially missed last state, if opponent and I play
532 !!this.game.mycolor &&
533 this.game.type == "live" &&
534 this.game.score == "*" &&
535 this.game.players.some(p => p.sid == user.sid)
537 this.send("asklastate", { target: user.sid });
539 this.askLastate = setInterval(
541 // Ask at most 3 times:
542 // if no reply after that there should be a network issue.
546 !!this.people[user.sid]
548 this.send("asklastate", { target: user.sid });
551 clearInterval(this.askLastate);
561 // Send current (live) game if not asked by any of the players
563 this.game.type == "live" &&
564 this.game.players.every(p => p.sid != data.from[0])
569 players: this.game.players,
571 cadence: this.game.cadence,
572 score: this.game.score
574 this.send("game", { data: myGame, target: data.from });
578 const gameToSend = Object.keys(this.game)
581 "id","fen","players","vid","cadence","fenStart","vname",
582 "moves","clocks","score","drawOffer","rematchOffer"
586 obj[k] = this.game[k];
591 this.send("fullgame", { data: gameToSend, target: data.from });
594 // Callback "roomInit" to poll clients only after game is loaded
595 this.loadVariantThenGame(data.data, this.roomInit);
598 // Sending informative last state if I played a move or score != "*"
599 // If the game or moves aren't loaded yet, delay the sending:
600 if (!this.game || !this.game.moves) this.lastateAsked = true;
601 else this.sendLastate(data.from);
604 // Got opponent infos about last move
605 this.gotLastate = true;
606 this.lastate = data.data;
607 if (this.game.rendered)
608 // Game is rendered (Board component)
609 this.processLastate();
610 // Else: will be processed when game is ready
614 const movePlus = data.data;
615 const movesCount = this.game.moves.length;
616 if (movePlus.index > movesCount) {
617 // This can only happen if I'm an observer and missed a move.
618 if (this.gotMoveIdx < movePlus.index)
619 this.gotMoveIdx = movePlus.index;
620 if (!this.gameIsLoading) this.askGameAgain();
624 movePlus.index < movesCount ||
625 this.gotMoveIdx >= movePlus.index
627 // Opponent re-send but we already have the move:
628 // (maybe he didn't receive our pingback...)
629 this.send("gotmove", {data: movePlus.index, target: data.from});
631 this.gotMoveIdx = movePlus.index;
632 const receiveMyMove = (movePlus.color == this.game.mycolor);
633 if (!receiveMyMove && !!this.game.mycolor)
634 // Notify opponent that I got the move:
635 this.send("gotmove", {data: movePlus.index, target: data.from});
636 if (movePlus.cancelDrawOffer) {
637 // Opponent refuses draw
639 // NOTE for corr games: drawOffer reset by player in turn
641 this.game.type == "live" &&
642 !!this.game.mycolor &&
645 GameStorage.update(this.gameRef, { drawOffer: "" });
648 this.$refs["basegame"].play(movePlus.move, "received", null, true);
649 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
650 this.game.clocks[moveColIdx] = movePlus.clock;
653 { receiveMyMove: receiveMyMove }
660 this.opponentGotMove = true;
661 // Now his clock starts running on my side:
662 const oppIdx = ['w','b'].indexOf(this.vr.turn);
667 const score = (data.data == "b" ? "1-0" : "0-1");
668 const side = (data.data == "w" ? "White" : "Black");
669 this.gameOver(score, side + " surrender");
672 this.gameOver("?", "Stop");
675 this.gameOver("1/2", data.data);
678 // NOTE: observers don't know who offered draw
679 this.drawOffer = "received";
680 if (this.game.type == "live") {
683 { drawOffer: V.GetOppCol(this.game.mycolor) }
688 // NOTE: observers don't know who offered rematch
689 this.rematchOffer = data.data ? "received" : "";
690 if (this.game.type == "live") {
693 { rematchOffer: V.GetOppCol(this.game.mycolor) }
698 // A game started, redirect if I'm playing in
699 const gameInfo = data.data;
700 const gameType = this.getGameType(gameInfo);
702 gameType == "live" &&
703 gameInfo.players.some(p => p.sid == this.st.user.sid)
705 this.addAndGotoLiveGame(gameInfo);
707 gameType == "corr" &&
708 gameInfo.players.some(p => p.id == this.st.user.id)
710 this.$router.push("/game/" + gameInfo.id);
712 this.rematchId = gameInfo.id;
713 document.getElementById("modalInfo").checked = true;
718 this.$refs["chatcomp"].newChat(data.data);
719 if (!document.getElementById("modalChat").checked)
720 document.getElementById("chatBtn").classList.add("somethingnew");
724 socketCloseListener: function() {
725 this.conn = new WebSocket(this.connexionString);
726 this.conn.addEventListener("message", this.socketMessageListener);
727 this.conn.addEventListener("close", this.socketCloseListener);
729 updateCorrGame: function(obj, callback) {
739 if (!!callback) callback();
744 sendLastate: function(target) {
745 // Send our "last state" informations to opponent
746 const L = this.game.moves.length;
747 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
750 (L > 0 && this.vr.turn != this.game.mycolor)
751 ? this.game.moves[L - 1]
753 clock: this.game.clocks[myIdx],
754 // Since we played a move (or abort or resign),
755 // only drawOffer=="sent" is possible
756 drawSent: this.drawOffer == "sent",
757 rematchSent: this.rematchOffer == "sent",
758 score: this.game.score != "*" ? this.game.score : undefined,
759 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
762 this.send("lastate", { data: myLastate, target: target });
764 // lastate was received, but maybe game wasn't ready yet:
765 processLastate: function() {
766 const data = this.lastate;
767 this.lastate = undefined; //security...
768 const L = this.game.moves.length;
769 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
770 this.game.clocks[oppIdx] = data.clock;
771 if (data.movesCount > L) {
772 // Just got last move from him
773 this.$refs["basegame"].play(data.lastMove, "received", null, true);
774 this.processMove(data.lastMove);
776 clearInterval(this.clockUpdate);
779 if (data.drawSent) this.drawOffer = "received";
780 if (data.rematchSent) this.rematchOffer = "received";
783 if (this.game.score == "*")
784 this.gameOver(data.score, data.scoreMsg);
787 clickDraw: function() {
788 if (!this.game.mycolor) return; //I'm just spectator
789 if (["received", "threerep"].includes(this.drawOffer)) {
790 if (!confirm(this.st.tr["Accept draw?"])) return;
792 this.drawOffer == "received"
794 : "Three repetitions";
795 this.send("draw", { data: message });
796 this.gameOver("1/2", message);
797 } else if (this.drawOffer == "") {
798 // No effect if drawOffer == "sent"
799 if (this.game.mycolor != this.vr.turn) {
800 alert(this.st.tr["Draw offer only in your turn"]);
803 if (!confirm(this.st.tr["Offer draw?"])) return;
804 this.drawOffer = "sent";
805 this.send("drawoffer");
806 if (this.game.type == "live") {
809 { drawOffer: this.game.mycolor }
811 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
814 addAndGotoLiveGame: function(gameInfo, callback) {
815 const game = Object.assign(
819 // (other) Game infos: constant
820 fenStart: gameInfo.fen,
821 vname: this.game.vname,
823 // Game state (including FEN): will be updated
825 clocks: [-1, -1], //-1 = unstarted
829 GameStorage.add(game, (err) => {
830 // No error expected.
832 if (this.st.settings.sound)
833 new Audio("/sounds/newgame.flac").play().catch(() => {});
834 if (!!callback) callback();
835 this.$router.push("/game/" + gameInfo.id);
839 clickRematch: function() {
840 if (!this.game.mycolor) return; //I'm just spectator
841 if (this.rematchOffer == "received") {
844 id: getRandString(), //ignored if corr
845 fen: V.GenRandInitFen(this.game.randomness),
846 players: this.game.players.reverse(),
848 cadence: this.game.cadence
850 const notifyNewGame = () => {
851 const oppsid = this.getOppsid(); //may be null
852 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
853 // To main Hall if corr game:
854 if (this.game.type == "corr")
855 this.send("newgame", { data: gameInfo });
856 // Also to MyGames page:
857 this.notifyMyGames("newgame", gameInfo);
859 if (this.game.type == "live")
860 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
867 // cid is useful to delete the challenge:
868 data: { gameInfo: gameInfo },
869 success: (response) => {
870 gameInfo.id = response.gameId;
872 this.$router.push("/game/" + response.gameId);
877 } else if (this.rematchOffer == "") {
878 this.rematchOffer = "sent";
879 this.send("rematchoffer", { data: true });
880 if (this.game.type == "live") {
883 { rematchOffer: this.game.mycolor }
885 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
886 } else if (this.rematchOffer == "sent") {
887 // Toggle rematch offer (on --> off)
888 this.rematchOffer = "";
889 this.send("rematchoffer", { data: false });
890 if (this.game.type == "live") {
895 } else this.updateCorrGame({ rematchOffer: 'n' });
898 abortGame: function() {
899 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
900 this.gameOver("?", "Stop");
904 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
906 this.send("resign", { data: this.game.mycolor });
907 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
908 const side = (this.game.mycolor == "w" ? "White" : "Black");
909 this.gameOver(score, side + " surrender");
911 loadGame: function(game, callback) {
912 this.vr = new V(game.fen);
913 const gtype = this.getGameType(game);
914 const tc = extractTime(game.cadence);
915 const myIdx = game.players.findIndex(p => {
916 return p.sid == this.st.user.sid || p.id == this.st.user.id;
918 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
919 if (!game.chats) game.chats = []; //live games don't have chat history
920 if (gtype == "corr") {
921 // NOTE: clocks in seconds
922 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
923 game.clocks = [tc.mainTime, tc.mainTime];
924 const L = game.moves.length;
925 if (game.score == "*") {
928 game.clocks[L % 2] -=
929 (Date.now() - game.moves[L-1].played) / 1000;
932 // Sort chat messages from newest to oldest
933 game.chats.sort((c1, c2) => {
934 return c2.added - c1.added;
936 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
937 // Did a chat message arrive after my last move?
939 if (L == 1 && myIdx == 0)
940 dtLastMove = game.moves[0].played;
943 // It's now white turn
944 dtLastMove = game.moves[L-1-(1-myIdx)].played;
947 dtLastMove = game.moves[L-1-myIdx].played;
950 if (dtLastMove < game.chats[0].added)
951 document.getElementById("chatBtn").classList.add("somethingnew");
953 // Now that we used idx and played, re-format moves as for live games
954 game.moves = game.moves.map(m => m.squares);
956 if (gtype == "live") {
957 if (game.clocks[0] < 0) {
958 // Game is unstarted. clock is ignored until move 2
959 game.clocks = [tc.mainTime, tc.mainTime];
961 // I play in this live game
962 GameStorage.update(game.id, {
968 // It's my turn: clocks not updated yet
969 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
972 // TODO: merge next 2 "if" conditions
973 if (!!game.drawOffer) {
974 if (game.drawOffer == "t")
976 this.drawOffer = "threerep";
978 // Draw offered by any of the players:
979 if (myIdx < 0) this.drawOffer = "received";
981 // I play in this game:
983 (game.drawOffer == "w" && myIdx == 0) ||
984 (game.drawOffer == "b" && myIdx == 1)
986 this.drawOffer = "sent";
987 else this.drawOffer = "received";
991 if (!!game.rematchOffer) {
992 if (myIdx < 0) this.rematchOffer = "received";
994 // I play in this game:
996 (game.rematchOffer == "w" && myIdx == 0) ||
997 (game.rematchOffer == "b" && myIdx == 1)
999 this.rematchOffer = "sent";
1000 else this.rematchOffer = "received";
1003 this.repeat = {}; //reset: scan past moves' FEN:
1005 let vr_tmp = new V(game.fenStart);
1007 game.moves.forEach(m => {
1008 playMove(m, vr_tmp);
1009 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1010 this.repeat[fenIdx] = this.repeat[fenIdx]
1011 ? this.repeat[fenIdx] + 1
1014 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1015 this.game = Object.assign(
1016 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1019 increment: tc.increment,
1021 // opponent sid not strictly required (or available), but easier
1022 // at least oppsid or oppid is available anyway:
1023 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1024 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1028 this.$refs["basegame"].re_setVariables(this.game);
1029 if (!this.gameIsLoading) {
1031 this.gotMoveIdx = game.moves.length - 1;
1032 // If we arrive here after 'nextGame' action, the board might be hidden
1033 let boardDiv = document.querySelector(".game");
1034 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1035 boardDiv.style.visibility = "visible";
1037 this.re_setClocks();
1038 this.$nextTick(() => {
1039 this.game.rendered = true;
1040 // Did lastate arrive before game was rendered?
1041 if (this.lastate) this.processLastate();
1043 if (this.lastateAsked) {
1044 this.lastateAsked = false;
1045 this.sendLastate(game.oppsid);
1047 if (this.gameIsLoading) {
1048 this.gameIsLoading = false;
1049 if (this.gotMoveIdx >= game.moves.length)
1050 // Some moves arrived meanwhile...
1051 this.askGameAgain();
1053 if (!!callback) callback();
1055 loadVariantThenGame: async function(game, callback) {
1056 await import("@/variants/" + game.vname + ".js")
1057 .then((vModule) => {
1058 window.V = vModule[game.vname + "Rules"];
1059 this.loadGame(game, callback);
1062 // 3 cases for loading a game:
1063 // - from indexedDB (running or completed live game I play)
1064 // - from server (one correspondance game I play[ed] or not)
1065 // - from remote peer (one live game I don't play, finished or not)
1066 fetchGame: function(callback) {
1067 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1068 // corr games identifiers are integers
1073 data: { gid: this.gameRef },
1075 res.game.moves.forEach(m => {
1076 m.squares = JSON.parse(m.squares);
1083 // Local game (or live remote)
1084 GameStorage.get(this.gameRef, callback);
1086 re_setClocks: function() {
1087 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1088 if (this.game.moves.length < 2 || this.game.score != "*") {
1089 // 1st move not completed yet, or game over: freeze time
1092 const currentTurn = this.vr.turn;
1093 const currentMovesCount = this.game.moves.length;
1094 const colorIdx = ["w", "b"].indexOf(currentTurn);
1095 this.clockUpdate = setInterval(
1098 this.game.clocks[colorIdx] < 0 ||
1099 this.game.moves.length > currentMovesCount ||
1100 this.game.score != "*"
1102 clearInterval(this.clockUpdate);
1103 if (this.game.clocks[colorIdx] < 0)
1105 currentTurn == "w" ? "0-1" : "1-0",
1112 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1119 // Update variables and storage after a move:
1120 processMove: function(move, data) {
1121 if (!data) data = {};
1122 const moveCol = this.vr.turn;
1123 const colorIdx = ["w", "b"].indexOf(moveCol);
1124 const nextIdx = 1 - colorIdx;
1125 const doProcessMove = () => {
1126 const origMovescount = this.game.moves.length;
1127 // The move is (about to be) played: stop clock
1128 clearInterval(this.clockUpdate);
1129 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1130 if (this.drawOffer == "received")
1132 this.drawOffer = "";
1133 if (this.game.type == "live" && origMovescount >= 2) {
1134 this.game.clocks[colorIdx] += this.game.increment;
1135 // For a correct display in casqe of disconnected opponent:
1139 ppt(this.game.clocks[colorIdx]).split(':')
1141 GameStorage.update(this.gameRef, {
1142 // It's not my turn anymore:
1147 // Update current game object:
1148 playMove(move, this.vr);
1150 // Received move, score is computed in BaseGame, but maybe not yet.
1151 // ==> Compute it here, although this is redundant (TODO)
1152 data.score = this.vr.getCurrentScore();
1153 if (data.score != "*") this.gameOver(data.score);
1154 this.game.moves.push(move);
1155 this.game.fen = this.vr.getFen();
1156 if (this.game.type == "corr") {
1157 // In corr games, just reset clock to mainTime:
1158 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1160 // If repetition detected, consider that a draw offer was received:
1161 const fenObj = this.vr.getFenForRepeat();
1162 this.repeat[fenObj] =
1163 !!this.repeat[fenObj]
1164 ? this.repeat[fenObj] + 1
1166 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1167 else if (this.drawOffer == "threerep") this.drawOffer = "";
1168 if (!!this.game.mycolor && !data.receiveMyMove) {
1169 // NOTE: 'var' to see that variable outside this block
1170 var filtered_move = getFilteredMove(move);
1172 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1173 // Notify turn on MyGames page:
1182 // Since corr games are stored at only one location, update should be
1183 // done only by one player for each move:
1185 this.game.type == "live" &&
1186 !!this.game.mycolor &&
1187 moveCol != this.game.mycolor &&
1188 this.game.moves.length >= 2
1190 // Receive a move: update initime
1191 this.game.initime = Date.now();
1192 GameStorage.update(this.gameRef, {
1193 // It's my turn now!
1194 initime: this.game.initime
1198 !!this.game.mycolor &&
1199 !data.receiveMyMove &&
1200 (this.game.type == "live" || moveCol == this.game.mycolor)
1203 switch (this.drawOffer) {
1208 drawCode = this.game.mycolor;
1211 drawCode = V.GetOppCol(this.game.mycolor);
1214 if (this.game.type == "corr") {
1215 // corr: only move, fen and score
1216 this.updateCorrGame({
1219 squares: filtered_move,
1222 // Code "n" for "None" to force reset (otherwise it's ignored)
1223 drawOffer: drawCode || "n"
1227 const updateStorage = () => {
1228 GameStorage.update(this.gameRef, {
1230 move: filtered_move,
1231 moveIdx: origMovescount,
1232 clocks: this.game.clocks,
1236 // The active tab can update storage immediately
1237 if (!document.hidden) updateStorage();
1238 // Small random delay otherwise
1239 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1242 // Send move ("newmove" event) to people in the room (if our turn)
1243 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1245 move: filtered_move,
1246 index: origMovescount,
1247 // color is required to check if this is my move (if several tabs opened)
1249 cancelDrawOffer: this.drawOffer == ""
1251 if (this.game.type == "live")
1252 sendMove["clock"] = this.game.clocks[colorIdx];
1253 // (Live) Clocks will re-start when the opponent pingback arrive
1254 this.opponentGotMove = false;
1255 this.send("newmove", {data: sendMove});
1256 // If the opponent doesn't reply gotmove soon enough, re-send move:
1257 // Do this at most 2 times, because mpore would mean network issues,
1258 // opponent would then be expected to disconnect/reconnect.
1260 const currentUrl = document.location.href;
1261 this.retrySendmove = setInterval(
1265 this.opponentGotMove ||
1266 document.location.href != currentUrl //page change
1268 clearInterval(this.retrySendmove);
1271 const oppsid = this.getOppsid();
1273 // Opponent is disconnected: he'll ask last state
1274 clearInterval(this.retrySendmove);
1276 this.send("newmove", { data: sendMove, target: oppsid });
1284 // Not my move or I'm an observer: just start other player's clock
1285 this.re_setClocks();
1288 this.game.type == "corr" &&
1289 moveCol == this.game.mycolor &&
1292 let boardDiv = document.querySelector(".game");
1293 const afterSetScore = () => {
1295 if (this.st.settings.gotonext && this.nextIds.length > 0)
1296 this.showNextGame();
1298 // The board might have been hidden:
1299 if (boardDiv.style.visibility == "hidden")
1300 boardDiv.style.visibility = "visible";
1301 if (data.score == "*") this.re_setClocks();
1304 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1305 // We may play several moves in a row: in case of, remove listener:
1306 let elClone = el.cloneNode(true);
1307 el.parentNode.replaceChild(elClone, el);
1308 elClone.addEventListener(
1311 document.getElementById("modalConfirm").checked = false;
1312 if (!!data.score && data.score != "*")
1314 this.gameOver(data.score, null, afterSetScore);
1315 else afterSetScore();
1318 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1319 V.PlayOnBoard(this.vr.board, move);
1320 const position = this.vr.getBaseFen();
1321 V.UndoOnBoard(this.vr.board, move);
1322 if (["all","byrow"].includes(V.ShowMoves)) {
1323 this.curDiag = getDiagram({
1325 orientation: V.CanFlip ? this.game.mycolor : "w"
1327 document.querySelector("#confirmDiv > .card").style.width =
1328 boardDiv.offsetWidth + "px";
1330 // Incomplete information: just ask confirmation
1331 // Hide the board, because otherwise it could reveal infos
1332 boardDiv.style.visibility = "hidden";
1333 this.moveNotation = getFullNotation(move);
1335 document.getElementById("modalConfirm").checked = true;
1339 if (!!data.score && data.score != "*")
1340 this.gameOver(data.score, null, doProcessMove);
1341 else doProcessMove();
1344 cancelMove: function() {
1345 let boardDiv = document.querySelector(".game");
1346 if (boardDiv.style.visibility == "hidden")
1347 boardDiv.style.visibility = "visible";
1348 document.getElementById("modalConfirm").checked = false;
1349 this.$refs["basegame"].cancelLastMove();
1351 // In corr games, callback to change page only after score is set:
1352 gameOver: function(score, scoreMsg, callback) {
1353 this.game.score = score;
1354 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1355 this.game.scoreMsg = scoreMsg;
1356 this.$set(this.game, "scoreMsg", scoreMsg);
1357 const myIdx = this.game.players.findIndex(p => {
1358 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1361 // OK, I play in this game
1366 if (this.game.type == "live") {
1367 GameStorage.update(this.gameRef, scoreObj);
1368 if (!!callback) callback();
1370 else this.updateCorrGame(scoreObj, callback);
1371 // Notify the score to main Hall. TODO: only one player (currently double send)
1372 this.send("result", { gid: this.game.id, score: score });
1373 // Also to MyGames page (TODO: doubled as well...)
1382 else if (!!callback) callback();
1388 <style lang="sass" scoped>
1394 background-color: lightgreen
1406 @media screen and (min-width: 768px)
1409 @media screen and (max-width: 767px)
1414 display: inline-block
1418 display: inline-block
1420 display: inline-flex
1424 @media screen and (max-width: 767px)
1427 @media screen and (max-width: 767px)
1430 @media screen and (min-width: 768px)
1442 background-color: #edda99
1444 display: inline-block
1453 display: inline-block
1466 animation: blink-animation 2s steps(3, start) infinite
1467 @keyframes blink-animation
1472 display: inline-block
1484 .draw-sent, .draw-sent:hover
1485 background-color: lightyellow
1487 .draw-received, .draw-received:hover
1488 background-color: lightgreen
1490 .draw-threerep, .draw-threerep:hover
1491 background-color: #e4d1fc
1493 .rematch-sent, .rematch-sent:hover
1494 background-color: lightyellow
1496 .rematch-received, .rematch-received:hover
1497 background-color: lightgreen
1500 background-color: #c5fefe
1513 background-color: lightgreen
1515 background-color: red