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="participateInChat(p)"
32 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
35 :players="game.players"
36 :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 { notify } from "@/utils/notifications";
135 import { ajax } from "@/utils/ajax";
136 import { extractTime } from "@/utils/timeControl";
137 import { getRandString } from "@/utils/alea";
138 import { getScoreMessage } from "@/utils/scoring";
139 import { getFullNotation } from "@/utils/notation";
140 import { getDiagram } from "@/utils/printDiagram";
141 import { processModalClick } from "@/utils/modalClick";
142 import { playMove, getFilteredMove } from "@/utils/playUndo";
143 import { ArrayFun } from "@/utils/array";
144 import params from "@/parameters";
154 // gameRef can point to a corr game, local game or remote live game
157 game: {}, //passed to BaseGame
159 // virtualClocks will be initialized from true game.clocks
161 vr: null, //"variant rules" object initialized from FEN
166 people: {}, //players + observers
167 lastate: undefined, //used if opponent send lastate before game is ready
168 repeat: {}, //detect position repetition
169 curDiag: "", //for corr moves confirmation
171 roomInitialized: false,
172 // If newmove has wrong index: ask fullgame again:
174 gameIsLoading: false,
175 // If asklastate got no reply, ask again:
177 gotMoveIdx: -1, //last move index received
178 // If newmove got no pingback, send again:
179 opponentGotMove: false,
181 socketCloseListener: 0,
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(0, 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 clearInterval(this.socketCloseListener);
233 document.removeEventListener('visibilitychange', this.visibilityChange);
234 window.removeEventListener('focus', this.onFocus);
235 window.removeEventListener('blur', this.onBlur);
236 if (!!this.askLastate) clearInterval(this.askLastate);
237 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
238 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
239 this.conn.removeEventListener("message", this.socketMessageListener);
240 this.send("disconnect");
243 visibilityChange: function() {
244 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
245 this.focus = (document.visibilityState == "visible");
246 if (!this.focus && !!this.rematchOffer) {
247 this.rematchOffer = "";
248 this.send("rematchoffer", { data: false });
249 // Do not remove rematch offer from (local) storage
251 this.send(this.focus ? "getfocus" : "losefocus");
253 onFocus: function() {
255 this.send("getfocus");
259 if (!!this.rematchOffer) {
260 this.rematchOffer = "";
261 this.send("rematchoffer", { data: false });
263 this.send("losefocus");
265 participateInChat: function(p) {
266 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
268 someAnonymousPresent: function() {
270 Object.values(this.people).some(p =>
271 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
275 atCreation: function() {
276 document.addEventListener('visibilitychange', this.visibilityChange);
277 window.addEventListener('focus', this.onFocus);
278 window.addEventListener('blur', this.onBlur);
279 // 0] (Re)Set variables
280 this.gameRef = this.$route.params["id"];
281 // next = next corr games IDs to navigate faster (if applicable)
282 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
283 // Always add myself to players' list
284 const my = this.st.user;
285 const tmpId = getRandString();
293 tmpId: { focus: true }
298 players: [{ name: "" }, { name: "" }],
302 let chatComp = this.$refs["chatcomp"];
303 if (!!chatComp) chatComp.chats = [];
304 this.virtualClocks = [[0,0], [0,0]];
307 this.lastateAsked = false;
308 this.rematchOffer = "";
309 this.lastate = undefined;
310 this.roomInitialized = false;
311 this.askGameTime = 0;
312 this.gameIsLoading = false;
313 this.gotLastate = false;
314 this.gotMoveIdx = -1;
315 this.opponentGotMove = false;
316 this.askLastate = null;
317 this.retrySendmove = null;
318 this.clockUpdate = null;
319 this.newConnect = {};
321 // 1] Initialize connection
322 this.connexionString =
324 "/?sid=" + this.st.user.sid +
325 "&id=" + this.st.user.id +
328 // Discard potential "/?next=[...]" for page indication:
329 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
330 this.conn = new WebSocket(this.connexionString);
331 this.conn.addEventListener("message", this.socketMessageListener);
332 this.socketCloseListener = setInterval(
334 if (this.conn.readyState == 3) {
335 this.conn.removeEventListener("message", this.socketMessageListener);
336 this.conn = new WebSocket(this.connexionString);
337 this.conn.addEventListener("message", this.socketMessageListener);
342 // Socket init required before loading remote game:
343 const socketInit = callback => {
344 if (this.conn.readyState == 1)
348 // Socket not ready yet (initial loading)
349 // NOTE: first arg is Websocket object, unused here:
350 this.conn.onopen = () => callback();
352 this.fetchGame((game) => {
354 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
356 // Live game stored remotely: need socket to retrieve it
357 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
358 // --> It will be given when receiving "fullgame" socket event.
359 socketInit(() => { this.send("askfullgame"); });
362 roomInit: function() {
363 if (!this.roomInitialized) {
364 // Notify the room only now that I connected, because
365 // messages might be lost otherwise (if game loading is slow)
366 this.send("connect");
367 this.send("pollclients");
368 // We may ask fullgame several times if some moves are lost,
369 // but room should be init only once:
370 this.roomInitialized = true;
373 send: function(code, obj) {
375 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
377 isConnected: function(index) {
378 const player = this.game.players[index];
379 // Is it me ? In this case no need to bother with focus
380 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
381 // Still have to check for name (because of potential multi-accounts
382 // on same browser, although this should be rare...)
383 return (!this.st.user.name || this.st.user.name == player.name);
384 // Try to find a match in people:
388 Object.keys(this.people).some(sid => {
391 Object.values(this.people[sid].tmpIds).some(v => v.focus)
398 Object.values(this.people).some(p => {
401 Object.values(p.tmpIds).some(v => v.focus)
407 getOppsid: function() {
408 let oppsid = this.game.oppsid;
410 oppsid = Object.keys(this.people).find(
411 sid => this.people[sid].id == this.game.oppid
414 // oppsid is useful only if opponent is online:
415 if (!!oppsid && !!this.people[oppsid]) return oppsid;
418 toggleChat: function() {
419 if (document.getElementById("modalChat").checked)
421 document.getElementById("inputChat").focus();
422 // TODO: next line is only required when exiting chat,
423 // but the event for now isn't well detected.
424 document.getElementById("chatBtn").classList.remove("somethingnew");
426 processChat: function(chat) {
427 this.send("newchat", { data: chat });
428 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
429 if (this.game.type == "corr" && this.st.user.id > 0)
430 this.updateCorrGame({ chat: chat });
431 else if (this.game.type == "live") {
432 chat.added = Date.now();
433 GameStorage.update(this.gameRef, { chat: chat });
436 clearChat: function() {
437 if (!!this.game.mycolor) {
438 if (this.game.type == "corr") {
442 { data: { gid: this.game.id } }
446 GameStorage.update(this.gameRef, { delchat: true });
448 this.$set(this.game, "chats", []);
451 getGameType: function(game) {
452 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
454 // Notify something after a new move (to opponent and me on MyGames page)
455 notifyMyGames: function(thing, data) {
460 targets: this.game.players.map(p => {
461 return { sid: p.sid, id: p.id };
466 showNextGame: function() {
467 // Did I play in current game? If not, add it to nextIds list
468 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
469 this.nextIds.unshift(this.game.id);
470 const nextGid = this.nextIds.pop();
472 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
474 askGameAgain: function() {
475 this.gameIsLoading = true;
476 const currentUrl = document.location.href;
477 const doAskGame = () => {
478 if (document.location.href != currentUrl) return; //page change
479 this.fetchGame((game) => {
481 // This is my game: just reload.
484 // Just ask fullgame again (once!), this is much simpler.
485 // If this fails, the user could just reload page :/
486 this.send("askfullgame");
489 // Delay of at least 2s between two game requests
490 const now = Date.now();
491 const delay = Math.max(2000 - (now - this.askGameTime), 0);
492 this.askGameTime = now;
493 setTimeout(doAskGame, delay);
495 socketMessageListener: function(msg) {
496 if (!this.conn) return;
497 const data = JSON.parse(msg.data);
500 // TODO: shuffling and random filtering on server,
501 // if the room is really crowded.
502 Object.keys(data.sockIds).forEach(sid => {
503 if (sid != this.st.user.sid) {
504 this.send("askidentity", { target: sid });
505 this.people[sid] = { tmpIds: data.sockIds[sid] };
507 // Complete my tmpIds:
508 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
513 if (!this.people[data.from[0]]) {
514 // focus depends on the tmpId (e.g. tab)
520 [data.from[1]]: { focus: true }
524 this.newConnect[data.from] = true; //for self multi-connects tests
525 this.send("askidentity", { target: data.from[0] });
527 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
528 this.$forceUpdate(); //TODO: shouldn't be required
532 if (!this.people[data.from[0]]) return;
533 delete this.people[data.from[0]].tmpIds[data.from[1]];
534 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
535 this.$delete(this.people, data.from[0]);
536 else this.$forceUpdate(); //TODO: shouldn't be required
539 let player = this.people[data.from[0]];
541 player.tmpIds[data.from[1]].focus = true;
542 this.$forceUpdate(); //TODO: shouldn't be required
547 let player = this.people[data.from[0]];
549 player.tmpIds[data.from[1]].focus = false;
550 this.$forceUpdate(); //TODO: shouldn't be required
555 // I logged in elsewhere:
556 this.conn.removeEventListener("message", this.socketMessageListener);
557 this.conn.removeEventListener("close", this.socketCloseListener);
559 alert(this.st.tr["New connexion detected: tab now offline"]);
561 case "askidentity": {
562 // Request for identification
564 // Decompose to avoid revealing email
565 name: this.st.user.name,
566 sid: this.st.user.sid,
569 this.send("identity", { data: me, target: data.from });
573 const user = data.data;
574 let player = this.people[user.sid];
575 // player.tmpIds is already set
576 player.name = user.name;
578 this.$forceUpdate(); //TODO: shouldn't be required
579 // If I multi-connect, kill current connexion if no mark (I'm older)
580 if (this.newConnect[user.sid]) {
583 user.id == this.st.user.id &&
584 user.sid != this.st.user.sid &&
585 !this.killed[this.st.user.sid]
587 this.send("killme", { sid: this.st.user.sid });
588 this.killed[this.st.user.sid] = true;
590 delete this.newConnect[user.sid];
592 if (!this.killed[this.st.user.sid]) {
593 // Ask potentially missed last state, if opponent and I play
596 !!this.game.mycolor &&
597 this.game.type == "live" &&
598 this.game.score == "*" &&
599 this.game.players.some(p => p.sid == user.sid)
601 this.send("asklastate", { target: user.sid });
603 this.askLastate = setInterval(
605 // Ask at most 3 times:
606 // if no reply after that there should be a network issue.
610 !!this.people[user.sid]
612 this.send("asklastate", { target: user.sid });
615 clearInterval(this.askLastate);
625 // Send current (live) game if not asked by any of the players
627 this.game.type == "live" &&
628 this.game.players.every(p => p.sid != data.from[0])
633 players: this.game.players,
635 cadence: this.game.cadence,
636 score: this.game.score
638 this.send("game", { data: myGame, target: data.from });
642 const gameToSend = Object.keys(this.game)
645 "id","fen","players","vid","cadence","fenStart","vname",
646 "moves","clocks","score","drawOffer","rematchOffer"
650 obj[k] = this.game[k];
655 this.send("fullgame", { data: gameToSend, target: data.from });
658 if (!!data.data.empty) {
659 alert(this.st.tr["The game should be in another tab"]);
663 // Callback "roomInit" to poll clients only after game is loaded
664 this.loadVariantThenGame(data.data, this.roomInit);
667 // Sending informative last state if I played a move or score != "*"
668 // If the game or moves aren't loaded yet, delay the sending:
669 // TODO: since socket init after game load, the game is supposedly ready
670 if (!this.game || !this.game.moves) this.lastateAsked = true;
671 else this.sendLastate(data.from);
674 // Got opponent infos about last move
675 this.gotLastate = true;
676 this.lastate = data.data;
677 if (this.game.rendered)
678 // Game is rendered (Board component)
679 this.processLastate();
680 // Else: will be processed when game is ready
684 const movePlus = data.data;
685 const movesCount = this.game.moves.length;
686 if (movePlus.index > movesCount) {
687 // This can only happen if I'm an observer and missed a move.
688 if (this.gotMoveIdx < movePlus.index)
689 this.gotMoveIdx = movePlus.index;
690 if (!this.gameIsLoading) this.askGameAgain();
694 movePlus.index < movesCount ||
695 this.gotMoveIdx >= movePlus.index
697 // Opponent re-send but we already have the move:
698 // (maybe he didn't receive our pingback...)
699 this.send("gotmove", {data: movePlus.index, target: data.from});
701 this.gotMoveIdx = movePlus.index;
702 const receiveMyMove = (movePlus.color == this.game.mycolor);
703 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
704 if (!receiveMyMove && !!this.game.mycolor) {
705 // Notify opponent that I got the move:
706 this.send("gotmove", {data: movePlus.index, target: data.from});
707 // And myself if I'm elsewhere:
713 (this.game.players[moveColIdx].name || "@nonymous") +
719 if (movePlus.cancelDrawOffer) {
720 // Opponent refuses draw
722 // NOTE for corr games: drawOffer reset by player in turn
724 this.game.type == "live" &&
725 !!this.game.mycolor &&
728 GameStorage.update(this.gameRef, { drawOffer: "" });
731 this.$refs["basegame"].play(movePlus.move, "received", null, true);
732 this.game.clocks[moveColIdx] = movePlus.clock;
735 { receiveMyMove: receiveMyMove }
742 this.opponentGotMove = true;
743 // Now his clock starts running on my side:
744 const oppIdx = ['w','b'].indexOf(this.vr.turn);
745 // NOTE: next line to avoid multi-resetClocks when several tabs
746 // on same game, resulting in a faster countdown.
747 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
752 const score = (data.data == "b" ? "1-0" : "0-1");
753 const side = (data.data == "w" ? "White" : "Black");
754 this.gameOver(score, side + " surrender");
757 this.gameOver("?", "Stop");
760 this.gameOver("1/2", data.data);
763 // NOTE: observers don't know who offered draw
764 this.drawOffer = "received";
765 if (this.game.type == "live") {
768 { drawOffer: V.GetOppCol(this.game.mycolor) }
773 // NOTE: observers don't know who offered rematch
774 this.rematchOffer = data.data ? "received" : "";
775 if (this.game.type == "live") {
778 { rematchOffer: V.GetOppCol(this.game.mycolor) }
783 // A game started, redirect if I'm playing in
784 const gameInfo = data.data;
785 const gameType = this.getGameType(gameInfo);
787 gameType == "live" &&
788 gameInfo.players.some(p => p.sid == this.st.user.sid)
790 this.addAndGotoLiveGame(gameInfo);
792 gameType == "corr" &&
793 gameInfo.players.some(p => p.id == this.st.user.id)
795 this.$router.push("/game/" + gameInfo.id);
797 this.rematchId = gameInfo.id;
798 document.getElementById("modalInfo").checked = true;
803 let chat = data.data;
804 this.$refs["chatcomp"].newChat(chat);
805 if (this.game.type == "live") {
806 chat.added = Date.now();
807 GameStorage.update(this.gameRef, { chat: chat });
809 if (!document.getElementById("modalChat").checked)
810 document.getElementById("chatBtn").classList.add("somethingnew");
815 updateCorrGame: function(obj, callback) {
825 if (!!callback) callback();
830 sendLastate: function(target) {
831 // Send our "last state" informations to opponent
832 const L = this.game.moves.length;
833 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
836 (L > 0 && this.vr.turn != this.game.mycolor)
837 ? this.game.moves[L - 1]
839 clock: this.game.clocks[myIdx],
840 // Since we played a move (or abort or resign),
841 // only drawOffer=="sent" is possible
842 drawSent: this.drawOffer == "sent",
843 rematchSent: this.rematchOffer == "sent",
844 score: this.game.score != "*" ? this.game.score : undefined,
845 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
848 this.send("lastate", { data: myLastate, target: target });
850 // lastate was received, but maybe game wasn't ready yet:
851 processLastate: function() {
852 const data = this.lastate;
853 this.lastate = undefined; //security...
854 const L = this.game.moves.length;
855 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
856 this.game.clocks[oppIdx] = data.clock;
857 if (data.movesCount > L) {
858 // Just got last move from him
859 this.$refs["basegame"].play(data.lastMove, "received", null, true);
860 this.processMove(data.lastMove);
862 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
865 if (data.drawSent) this.drawOffer = "received";
866 if (data.rematchSent) this.rematchOffer = "received";
869 if (this.game.score == "*")
870 this.gameOver(data.score, data.scoreMsg);
873 clickDraw: function() {
874 if (!this.game.mycolor) return; //I'm just spectator
875 if (["received", "threerep"].includes(this.drawOffer)) {
876 if (!confirm(this.st.tr["Accept draw?"])) return;
878 this.drawOffer == "received"
880 : "Three repetitions";
881 this.send("draw", { data: message });
882 this.gameOver("1/2", message);
883 } else if (this.drawOffer == "") {
884 // No effect if drawOffer == "sent"
885 if (this.game.mycolor != this.vr.turn) {
886 alert(this.st.tr["Draw offer only in your turn"]);
889 if (!confirm(this.st.tr["Offer draw?"])) return;
890 this.drawOffer = "sent";
891 this.send("drawoffer");
892 if (this.game.type == "live") {
895 { drawOffer: this.game.mycolor }
897 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
900 addAndGotoLiveGame: function(gameInfo, callback) {
901 const game = Object.assign(
905 // (other) Game infos: constant
906 fenStart: gameInfo.fen,
907 vname: this.game.vname,
909 // Game state (including FEN): will be updated
911 clocks: [-1, -1], //-1 = unstarted
915 GameStorage.add(game, (err) => {
916 // No error expected.
918 if (this.st.settings.sound)
919 new Audio("/sounds/newgame.flac").play().catch(() => {});
920 if (!!callback) callback();
921 this.$router.push("/game/" + gameInfo.id);
925 clickRematch: function() {
926 if (!this.game.mycolor) return; //I'm just spectator
927 if (this.rematchOffer == "received") {
930 id: getRandString(), //ignored if corr
931 fen: V.GenRandInitFen(this.game.randomness),
932 players: this.game.players.reverse(),
934 cadence: this.game.cadence
936 const notifyNewGame = () => {
937 const oppsid = this.getOppsid(); //may be null
938 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
939 // To main Hall if corr game:
940 if (this.game.type == "corr")
941 this.send("newgame", { data: gameInfo, page: "/" });
942 // Also to MyGames page:
943 this.notifyMyGames("newgame", gameInfo);
945 if (this.game.type == "live")
946 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
953 // cid is useful to delete the challenge:
954 data: { gameInfo: gameInfo },
955 success: (response) => {
956 gameInfo.id = response.gameId;
958 this.$router.push("/game/" + response.gameId);
963 } else if (this.rematchOffer == "") {
964 this.rematchOffer = "sent";
965 this.send("rematchoffer", { data: true });
966 if (this.game.type == "live") {
969 { rematchOffer: this.game.mycolor }
971 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
972 } else if (this.rematchOffer == "sent") {
973 // Toggle rematch offer (on --> off)
974 this.rematchOffer = "";
975 this.send("rematchoffer", { data: false });
976 if (this.game.type == "live") {
981 } else this.updateCorrGame({ rematchOffer: 'n' });
984 abortGame: function() {
985 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
986 this.gameOver("?", "Stop");
990 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
992 this.send("resign", { data: this.game.mycolor });
993 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
994 const side = (this.game.mycolor == "w" ? "White" : "Black");
995 this.gameOver(score, side + " surrender");
997 loadGame: function(game, callback) {
998 this.vr = new V(game.fen);
999 const gtype = this.getGameType(game);
1000 const tc = extractTime(game.cadence);
1001 const myIdx = game.players.findIndex(p => {
1002 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1004 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
1005 // Live games before 26/03/2020 don't have chat history. TODO: remove next line
1006 if (!game.chats) game.chats = [];
1007 // Sort chat messages from newest to oldest
1008 game.chats.sort((c1, c2) => c2.added - c1.added);
1009 if (gtype == "corr") {
1010 // NOTE: clocks in seconds
1011 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1012 game.clocks = [tc.mainTime, tc.mainTime];
1013 const L = game.moves.length;
1014 if (game.score == "*") {
1017 game.clocks[L % 2] -=
1018 (Date.now() - game.moves[L-1].played) / 1000;
1021 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
1022 // Did a chat message arrive after my last move?
1024 if (L == 1 && myIdx == 0)
1025 dtLastMove = game.moves[0].played;
1028 // It's now white turn
1029 dtLastMove = game.moves[L-1-(1-myIdx)].played;
1032 dtLastMove = game.moves[L-1-myIdx].played;
1035 if (dtLastMove < game.chats[0].added)
1036 document.getElementById("chatBtn").classList.add("somethingnew");
1038 // Now that we used idx and played, re-format moves as for live games
1039 game.moves = game.moves.map(m => m.squares);
1041 if (gtype == "live") {
1043 game.chats.length > 0 &&
1044 (!game.initime || game.initime < game.chats[0].added)
1046 document.getElementById("chatBtn").classList.add("somethingnew");
1048 if (game.clocks[0] < 0) {
1049 // Game is unstarted. clock is ignored until move 2
1050 game.clocks = [tc.mainTime, tc.mainTime];
1052 // I play in this live game
1053 GameStorage.update(game.id, {
1059 // It's my turn: clocks not updated yet
1060 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1063 // TODO: merge next 2 "if" conditions
1064 if (!!game.drawOffer) {
1065 if (game.drawOffer == "t")
1066 // Three repetitions
1067 this.drawOffer = "threerep";
1069 // Draw offered by any of the players:
1070 if (myIdx < 0) this.drawOffer = "received";
1072 // I play in this game:
1074 (game.drawOffer == "w" && myIdx == 0) ||
1075 (game.drawOffer == "b" && myIdx == 1)
1077 this.drawOffer = "sent";
1078 else this.drawOffer = "received";
1082 if (!!game.rematchOffer) {
1083 if (myIdx < 0) this.rematchOffer = "received";
1085 // I play in this game:
1087 (game.rematchOffer == "w" && myIdx == 0) ||
1088 (game.rematchOffer == "b" && myIdx == 1)
1090 this.rematchOffer = "sent";
1091 else this.rematchOffer = "received";
1094 this.repeat = {}; //reset: scan past moves' FEN:
1096 let vr_tmp = new V(game.fenStart);
1098 game.moves.forEach(m => {
1099 playMove(m, vr_tmp);
1100 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1101 this.repeat[fenIdx] = this.repeat[fenIdx]
1102 ? this.repeat[fenIdx] + 1
1105 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1106 this.game = Object.assign(
1107 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1110 increment: tc.increment,
1112 // opponent sid not strictly required (or available), but easier
1113 // at least oppsid or oppid is available anyway:
1114 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1115 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1119 this.$refs["basegame"].re_setVariables(this.game);
1120 if (!this.gameIsLoading) {
1122 this.gotMoveIdx = game.moves.length - 1;
1123 // If we arrive here after 'nextGame' action, the board might be hidden
1124 let boardDiv = document.querySelector(".game");
1125 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1126 boardDiv.style.visibility = "visible";
1128 this.re_setClocks();
1129 this.$nextTick(() => {
1130 this.game.rendered = true;
1131 // Did lastate arrive before game was rendered?
1132 if (this.lastate) this.processLastate();
1134 if (this.lastateAsked) {
1135 this.lastateAsked = false;
1136 this.sendLastate(game.oppsid);
1138 if (this.gameIsLoading) {
1139 this.gameIsLoading = false;
1140 if (this.gotMoveIdx >= game.moves.length)
1141 // Some moves arrived meanwhile...
1142 this.askGameAgain();
1144 if (!!callback) callback();
1146 loadVariantThenGame: async function(game, callback) {
1147 await import("@/variants/" + game.vname + ".js")
1148 .then((vModule) => {
1149 window.V = vModule[game.vname + "Rules"];
1150 this.loadGame(game, callback);
1153 // 3 cases for loading a game:
1154 // - from indexedDB (running or completed live game I play)
1155 // - from server (one correspondance game I play[ed] or not)
1156 // - from remote peer (one live game I don't play, finished or not)
1157 fetchGame: function(callback) {
1158 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1159 // corr games identifiers are integers
1164 data: { gid: this.gameRef },
1166 res.game.moves.forEach(m => {
1167 m.squares = JSON.parse(m.squares);
1174 // Local game (or live remote)
1175 GameStorage.get(this.gameRef, callback);
1177 re_setClocks: function() {
1178 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1179 if (this.game.moves.length < 2 || this.game.score != "*") {
1180 // 1st move not completed yet, or game over: freeze time
1183 const currentTurn = this.vr.turn;
1184 const currentMovesCount = this.game.moves.length;
1185 const colorIdx = ["w", "b"].indexOf(currentTurn);
1186 this.clockUpdate = setInterval(
1189 this.game.clocks[colorIdx] < 0 ||
1190 this.game.moves.length > currentMovesCount ||
1191 this.game.score != "*"
1193 clearInterval(this.clockUpdate);
1194 this.clockUpdate = null;
1195 if (this.game.clocks[colorIdx] < 0)
1197 currentTurn == "w" ? "0-1" : "1-0",
1204 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1211 // Update variables and storage after a move:
1212 processMove: function(move, data) {
1213 if (!data) data = {};
1214 const moveCol = this.vr.turn;
1215 const colorIdx = ["w", "b"].indexOf(moveCol);
1216 const nextIdx = 1 - colorIdx;
1217 const doProcessMove = () => {
1218 const origMovescount = this.game.moves.length;
1219 // The move is (about to be) played: stop clock
1220 clearInterval(this.clockUpdate);
1221 this.clockUpdate = null;
1222 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1223 if (this.drawOffer == "received")
1225 this.drawOffer = "";
1226 if (this.game.type == "live" && origMovescount >= 2) {
1227 this.game.clocks[colorIdx] += this.game.increment;
1228 // For a correct display in casqe of disconnected opponent:
1232 ppt(this.game.clocks[colorIdx]).split(':')
1234 GameStorage.update(this.gameRef, {
1235 // It's not my turn anymore:
1240 // Update current game object:
1241 playMove(move, this.vr);
1243 // Received move, score is computed in BaseGame, but maybe not yet.
1244 // ==> Compute it here, although this is redundant (TODO)
1245 data.score = this.vr.getCurrentScore();
1246 if (data.score != "*") this.gameOver(data.score);
1247 this.game.moves.push(move);
1248 this.game.fen = this.vr.getFen();
1249 if (this.game.type == "corr") {
1250 // In corr games, just reset clock to mainTime:
1251 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1253 // If repetition detected, consider that a draw offer was received:
1254 const fenObj = this.vr.getFenForRepeat();
1255 this.repeat[fenObj] =
1256 !!this.repeat[fenObj]
1257 ? this.repeat[fenObj] + 1
1259 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1260 else if (this.drawOffer == "threerep") this.drawOffer = "";
1261 if (!!this.game.mycolor && !data.receiveMyMove) {
1262 // NOTE: 'var' to see that variable outside this block
1263 var filtered_move = getFilteredMove(move);
1265 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1266 // Notify turn on MyGames page:
1275 // Since corr games are stored at only one location, update should be
1276 // done only by one player for each move:
1278 this.game.type == "live" &&
1279 !!this.game.mycolor &&
1280 moveCol != this.game.mycolor &&
1281 this.game.moves.length >= 2
1283 // Receive a move: update initime
1284 this.game.initime = Date.now();
1285 GameStorage.update(this.gameRef, {
1286 // It's my turn now!
1287 initime: this.game.initime
1291 !!this.game.mycolor &&
1292 !data.receiveMyMove &&
1293 (this.game.type == "live" || moveCol == this.game.mycolor)
1296 switch (this.drawOffer) {
1301 drawCode = this.game.mycolor;
1304 drawCode = V.GetOppCol(this.game.mycolor);
1307 if (this.game.type == "corr") {
1308 // corr: only move, fen and score
1309 this.updateCorrGame({
1312 squares: filtered_move,
1315 // Code "n" for "None" to force reset (otherwise it's ignored)
1316 drawOffer: drawCode || "n"
1320 const updateStorage = () => {
1321 GameStorage.update(this.gameRef, {
1323 move: filtered_move,
1324 moveIdx: origMovescount,
1325 clocks: this.game.clocks,
1329 // The active tab can update storage immediately
1330 if (this.focus) updateStorage();
1331 // Small random delay otherwise
1332 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1335 // Send move ("newmove" event) to people in the room (if our turn)
1336 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1338 move: filtered_move,
1339 index: origMovescount,
1340 // color is required to check if this is my move (if several tabs opened)
1342 cancelDrawOffer: this.drawOffer == ""
1344 if (this.game.type == "live")
1345 sendMove["clock"] = this.game.clocks[colorIdx];
1346 // (Live) Clocks will re-start when the opponent pingback arrive
1347 this.opponentGotMove = false;
1348 this.send("newmove", {data: sendMove});
1349 // If the opponent doesn't reply gotmove soon enough, re-send move:
1350 // Do this at most 2 times, because mpore would mean network issues,
1351 // opponent would then be expected to disconnect/reconnect.
1353 const currentUrl = document.location.href;
1354 this.retrySendmove = setInterval(
1358 this.opponentGotMove ||
1359 document.location.href != currentUrl //page change
1361 clearInterval(this.retrySendmove);
1364 const oppsid = this.getOppsid();
1366 // Opponent is disconnected: he'll ask last state
1367 clearInterval(this.retrySendmove);
1369 this.send("newmove", { data: sendMove, target: oppsid });
1377 // Not my move or I'm an observer: just start other player's clock
1378 this.re_setClocks();
1381 this.game.type == "corr" &&
1382 moveCol == this.game.mycolor &&
1385 let boardDiv = document.querySelector(".game");
1386 const afterSetScore = () => {
1388 if (this.st.settings.gotonext && this.nextIds.length > 0)
1389 this.showNextGame();
1391 // The board might have been hidden:
1392 if (boardDiv.style.visibility == "hidden")
1393 boardDiv.style.visibility = "visible";
1394 if (data.score == "*") this.re_setClocks();
1397 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1398 // We may play several moves in a row: in case of, remove listener:
1399 let elClone = el.cloneNode(true);
1400 el.parentNode.replaceChild(elClone, el);
1401 elClone.addEventListener(
1404 document.getElementById("modalConfirm").checked = false;
1405 if (!!data.score && data.score != "*")
1407 this.gameOver(data.score, null, afterSetScore);
1408 else afterSetScore();
1411 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1412 V.PlayOnBoard(this.vr.board, move);
1413 const position = this.vr.getBaseFen();
1414 V.UndoOnBoard(this.vr.board, move);
1415 if (["all","byrow"].includes(V.ShowMoves)) {
1416 this.curDiag = getDiagram({
1418 orientation: V.CanFlip ? this.game.mycolor : "w"
1420 document.querySelector("#confirmDiv > .card").style.width =
1421 boardDiv.offsetWidth + "px";
1423 // Incomplete information: just ask confirmation
1424 // Hide the board, because otherwise it could reveal infos
1425 boardDiv.style.visibility = "hidden";
1426 this.moveNotation = getFullNotation(move);
1428 document.getElementById("modalConfirm").checked = true;
1432 if (!!data.score && data.score != "*")
1433 this.gameOver(data.score, null, doProcessMove);
1434 else doProcessMove();
1437 cancelMove: function() {
1438 let boardDiv = document.querySelector(".game");
1439 if (boardDiv.style.visibility == "hidden")
1440 boardDiv.style.visibility = "visible";
1441 document.getElementById("modalConfirm").checked = false;
1442 this.$refs["basegame"].cancelLastMove();
1444 // In corr games, callback to change page only after score is set:
1445 gameOver: function(score, scoreMsg, callback) {
1446 this.game.score = score;
1447 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1448 this.game.scoreMsg = scoreMsg;
1449 this.$set(this.game, "scoreMsg", scoreMsg);
1450 const myIdx = this.game.players.findIndex(p => {
1451 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1454 // OK, I play in this game
1459 if (this.game.type == "live") {
1460 GameStorage.update(this.gameRef, scoreObj);
1461 // Notify myself locally if I'm elsewhere:
1465 { body: score + " : " + scoreMsg }
1468 if (!!callback) callback();
1470 else this.updateCorrGame(scoreObj, callback);
1471 // Notify the score to main Hall. TODO: only one player (currently double send)
1472 this.send("result", { gid: this.game.id, score: score });
1473 // Also to MyGames page (TODO: doubled as well...)
1482 else if (!!callback) callback();
1488 <style lang="sass" scoped>
1494 background-color: lightgreen
1506 @media screen and (min-width: 768px)
1509 @media screen and (max-width: 767px)
1514 display: inline-block
1518 display: inline-block
1520 display: inline-flex
1524 @media screen and (max-width: 767px)
1527 @media screen and (max-width: 767px)
1530 @media screen and (min-width: 768px)
1542 background-color: #edda99
1544 display: inline-block
1553 display: inline-block
1566 animation: blink-animation 2s steps(3, start) infinite
1567 @keyframes blink-animation
1572 display: inline-block
1584 .draw-sent, .draw-sent:hover
1585 background-color: lightyellow
1587 .draw-received, .draw-received:hover
1588 background-color: lightgreen
1590 .draw-threerep, .draw-threerep:hover
1591 background-color: #e4d1fc
1593 .rematch-sent, .rematch-sent:hover
1594 background-color: lightyellow
1596 .rematch-received, .rematch-received:hover
1597 background-color: lightgreen
1600 background-color: #c5fefe
1613 background-color: lightgreen
1615 background-color: red