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
158 focus: !document.hidden, //will not always work... TODO
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(
336 "message", this.socketMessageListener);
337 this.conn = new WebSocket(this.connexionString);
338 this.conn.addEventListener("message", this.socketMessageListener);
343 // Socket init required before loading remote game:
344 const socketInit = callback => {
345 if (this.conn.readyState == 1)
349 // Socket not ready yet (initial loading)
350 // NOTE: first arg is Websocket object, unused here:
351 this.conn.onopen = () => callback();
353 this.fetchGame((game) => {
355 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
357 // Live game stored remotely: need socket to retrieve it
358 // NOTE: the callback "roomInit" will be lost, so it's not provided.
359 // --> It will be given when receiving "fullgame" socket event.
360 socketInit(() => { this.send("askfullgame"); });
363 roomInit: function() {
364 if (!this.roomInitialized) {
365 // Notify the room only now that I connected, because
366 // messages might be lost otherwise (if game loading is slow)
367 this.send("connect");
368 this.send("pollclients");
369 // We may ask fullgame several times if some moves are lost,
370 // but room should be init only once:
371 this.roomInitialized = true;
374 send: function(code, obj) {
376 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
378 isConnected: function(index) {
379 const player = this.game.players[index];
380 // Is it me ? In this case no need to bother with focus
381 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
382 // Still have to check for name (because of potential multi-accounts
383 // on same browser, although this should be rare...)
384 return (!this.st.user.name || this.st.user.name == player.name);
385 // Try to find a match in people:
389 Object.keys(this.people).some(sid => {
392 Object.values(this.people[sid].tmpIds).some(v => v.focus)
399 Object.values(this.people).some(p => {
402 Object.values(p.tmpIds).some(v => v.focus)
408 getOppsid: function() {
409 let oppsid = this.game.oppsid;
411 oppsid = Object.keys(this.people).find(
412 sid => this.people[sid].id == this.game.oppid
415 // oppsid is useful only if opponent is online:
416 if (!!oppsid && !!this.people[oppsid]) return oppsid;
419 toggleChat: function() {
420 if (document.getElementById("modalChat").checked)
422 document.getElementById("inputChat").focus();
423 // TODO: next line is only required when exiting chat,
424 // but the event for now isn't well detected.
425 document.getElementById("chatBtn").classList.remove("somethingnew");
427 processChat: function(chat) {
428 this.send("newchat", { data: chat });
429 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
430 if (this.game.type == "corr" && this.st.user.id > 0)
431 this.updateCorrGame({ chat: chat });
432 else if (this.game.type == "live") {
433 chat.added = Date.now();
434 GameStorage.update(this.gameRef, { chat: chat });
437 clearChat: function() {
438 if (!!this.game.mycolor) {
439 if (this.game.type == "corr") {
443 { data: { gid: this.game.id } }
447 GameStorage.update(this.gameRef, { delchat: true });
449 this.$set(this.game, "chats", []);
452 getGameType: function(game) {
453 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
455 // Notify something after a new move (to opponent and me on MyGames page)
456 notifyMyGames: function(thing, data) {
461 targets: this.game.players.map(p => {
462 return { sid: p.sid, id: p.id };
467 showNextGame: function() {
468 // Did I play in current game? If not, add it to nextIds list
469 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
470 this.nextIds.unshift(this.game.id);
471 const nextGid = this.nextIds.pop();
473 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
475 askGameAgain: function() {
476 this.gameIsLoading = true;
477 const currentUrl = document.location.href;
478 const doAskGame = () => {
479 if (document.location.href != currentUrl) return; //page change
480 this.fetchGame((game) => {
482 // This is my game: just reload.
485 // Just ask fullgame again (once!), this is much simpler.
486 // If this fails, the user could just reload page :/
487 this.send("askfullgame");
490 // Delay of at least 2s between two game requests
491 const now = Date.now();
492 const delay = Math.max(2000 - (now - this.askGameTime), 0);
493 this.askGameTime = now;
494 setTimeout(doAskGame, delay);
496 socketMessageListener: function(msg) {
497 if (!this.conn) return;
498 const data = JSON.parse(msg.data);
501 // TODO: shuffling and random filtering on server,
502 // if the room is really crowded.
503 Object.keys(data.sockIds).forEach(sid => {
504 if (sid != this.st.user.sid) {
505 this.send("askidentity", { target: sid });
506 this.people[sid] = { tmpIds: data.sockIds[sid] };
508 // Complete my tmpIds:
509 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
514 if (!this.people[data.from[0]]) {
515 // focus depends on the tmpId (e.g. tab)
521 [data.from[1]]: { focus: true }
525 this.newConnect[data.from] = true; //for self multi-connects tests
526 this.send("askidentity", { target: data.from[0] });
528 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
529 this.$forceUpdate(); //TODO: shouldn't be required
533 if (!this.people[data.from[0]]) return;
534 delete this.people[data.from[0]].tmpIds[data.from[1]];
535 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
536 this.$delete(this.people, data.from[0]);
537 else this.$forceUpdate(); //TODO: shouldn't be required
540 let player = this.people[data.from[0]];
542 player.tmpIds[data.from[1]].focus = true;
543 this.$forceUpdate(); //TODO: shouldn't be required
548 let player = this.people[data.from[0]];
550 player.tmpIds[data.from[1]].focus = false;
551 this.$forceUpdate(); //TODO: shouldn't be required
556 // I logged in elsewhere:
557 this.conn.removeEventListener("message", this.socketMessageListener);
558 this.conn.removeEventListener("close", this.socketCloseListener);
560 alert(this.st.tr["New connexion detected: tab now offline"]);
562 case "askidentity": {
563 // Request for identification
565 // Decompose to avoid revealing email
566 name: this.st.user.name,
567 sid: this.st.user.sid,
570 this.send("identity", { data: me, target: data.from });
574 const user = data.data;
575 let player = this.people[user.sid];
576 // player.tmpIds is already set
577 player.name = user.name;
579 this.$forceUpdate(); //TODO: shouldn't be required
580 // If I multi-connect, kill current connexion if no mark (I'm older)
581 if (this.newConnect[user.sid]) {
584 user.id == this.st.user.id &&
585 user.sid != this.st.user.sid &&
586 !this.killed[this.st.user.sid]
588 this.send("killme", { sid: this.st.user.sid });
589 this.killed[this.st.user.sid] = true;
591 delete this.newConnect[user.sid];
593 if (!this.killed[this.st.user.sid]) {
594 // Ask potentially missed last state, if opponent and I play
597 !!this.game.mycolor &&
598 this.game.type == "live" &&
599 this.game.score == "*" &&
600 this.game.players.some(p => p.sid == user.sid)
602 this.send("asklastate", { target: user.sid });
604 this.askLastate = setInterval(
606 // Ask at most 3 times:
607 // if no reply after that there should be a network issue.
611 !!this.people[user.sid]
613 this.send("asklastate", { target: user.sid });
616 clearInterval(this.askLastate);
626 // Send current (live) game if not asked by any of the players
628 this.game.type == "live" &&
629 this.game.players.every(p => p.sid != data.from[0])
634 players: this.game.players,
636 cadence: this.game.cadence,
637 score: this.game.score
639 this.send("game", { data: myGame, target: data.from });
643 const gameToSend = Object.keys(this.game)
646 "id","fen","players","vid","cadence","fenStart","vname",
647 "moves","clocks","score","drawOffer","rematchOffer"
651 obj[k] = this.game[k];
656 this.send("fullgame", { data: gameToSend, target: data.from });
659 if (!!data.data.empty) {
660 alert(this.st.tr["The game should be in another tab"]);
664 // Callback "roomInit" to poll clients only after game is loaded
665 this.loadVariantThenGame(data.data, this.roomInit);
668 // Sending informative last state if I played a move or score != "*"
669 // If the game or moves aren't loaded yet, delay the sending:
670 // TODO: socket init after game load, so the game is supposedly ready
671 if (!this.game || !this.game.moves) this.lastateAsked = true;
672 else this.sendLastate(data.from);
675 // Got opponent infos about last move
676 this.gotLastate = true;
677 this.lastate = data.data;
678 if (this.game.rendered)
679 // Game is rendered (Board component)
680 this.processLastate();
681 // Else: will be processed when game is ready
685 const movePlus = data.data;
686 const movesCount = this.game.moves.length;
687 if (movePlus.index > movesCount) {
688 // This can only happen if I'm an observer and missed a move.
689 if (this.gotMoveIdx < movePlus.index)
690 this.gotMoveIdx = movePlus.index;
691 if (!this.gameIsLoading) this.askGameAgain();
695 movePlus.index < movesCount ||
696 this.gotMoveIdx >= movePlus.index
698 // Opponent re-send but we already have the move:
699 // (maybe he didn't receive our pingback...)
700 this.send("gotmove", {data: movePlus.index, target: data.from});
702 this.gotMoveIdx = movePlus.index;
703 const receiveMyMove = (movePlus.color == this.game.mycolor);
704 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
705 if (!receiveMyMove && !!this.game.mycolor) {
706 // Notify opponent that I got the move:
709 { data: movePlus.index, target: data.from }
711 // And myself if I'm elsewhere:
717 (this.game.players[moveColIdx].name || "@nonymous") +
723 if (movePlus.cancelDrawOffer) {
724 // Opponent refuses draw
726 // NOTE for corr games: drawOffer reset by player in turn
728 this.game.type == "live" &&
729 !!this.game.mycolor &&
732 GameStorage.update(this.gameRef, { drawOffer: "" });
735 this.$refs["basegame"].play(
736 movePlus.move, "received", null, true);
737 this.game.clocks[moveColIdx] = movePlus.clock;
740 { receiveMyMove: receiveMyMove }
747 this.opponentGotMove = true;
748 // Now his clock starts running on my side:
749 const oppIdx = ['w','b'].indexOf(this.vr.turn);
750 // NOTE: next line to avoid multi-resetClocks when several tabs
751 // on same game, resulting in a faster countdown.
752 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
757 const score = (data.data == "b" ? "1-0" : "0-1");
758 const side = (data.data == "w" ? "White" : "Black");
759 this.gameOver(score, side + " surrender");
762 this.gameOver("?", "Stop");
765 this.gameOver("1/2", data.data);
768 // NOTE: observers don't know who offered draw
769 this.drawOffer = "received";
770 if (this.game.type == "live") {
773 { drawOffer: V.GetOppCol(this.game.mycolor) }
778 // NOTE: observers don't know who offered rematch
779 this.rematchOffer = data.data ? "received" : "";
780 if (this.game.type == "live") {
783 { rematchOffer: V.GetOppCol(this.game.mycolor) }
788 // A game started, redirect if I'm playing in
789 const gameInfo = data.data;
790 const gameType = this.getGameType(gameInfo);
792 gameType == "live" &&
793 gameInfo.players.some(p => p.sid == this.st.user.sid)
795 this.addAndGotoLiveGame(gameInfo);
797 gameType == "corr" &&
798 gameInfo.players.some(p => p.id == this.st.user.id)
800 this.$router.push("/game/" + gameInfo.id);
802 this.rematchId = gameInfo.id;
803 document.getElementById("modalInfo").checked = true;
808 let chat = data.data;
809 this.$refs["chatcomp"].newChat(chat);
810 if (this.game.type == "live") {
811 chat.added = Date.now();
812 GameStorage.update(this.gameRef, { chat: chat });
814 if (!document.getElementById("modalChat").checked)
815 document.getElementById("chatBtn").classList.add("somethingnew");
820 updateCorrGame: function(obj, callback) {
830 if (!!callback) callback();
835 sendLastate: function(target) {
836 // Send our "last state" informations to opponent
837 const L = this.game.moves.length;
838 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
841 (L > 0 && this.vr.turn != this.game.mycolor)
842 ? this.game.moves[L - 1]
844 clock: this.game.clocks[myIdx],
845 // Since we played a move (or abort or resign),
846 // only drawOffer=="sent" is possible
847 drawSent: this.drawOffer == "sent",
848 rematchSent: this.rematchOffer == "sent",
849 score: this.game.score != "*" ? this.game.score : undefined,
850 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
853 this.send("lastate", { data: myLastate, target: target });
855 // lastate was received, but maybe game wasn't ready yet:
856 processLastate: function() {
857 const data = this.lastate;
858 this.lastate = undefined; //security...
859 const L = this.game.moves.length;
860 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
861 this.game.clocks[oppIdx] = data.clock;
862 if (data.movesCount > L) {
863 // Just got last move from him
864 this.$refs["basegame"].play(data.lastMove, "received", null, true);
865 this.processMove(data.lastMove);
867 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
870 if (data.drawSent) this.drawOffer = "received";
871 if (data.rematchSent) this.rematchOffer = "received";
874 if (this.game.score == "*")
875 this.gameOver(data.score, data.scoreMsg);
878 clickDraw: function() {
879 if (!this.game.mycolor) return; //I'm just spectator
880 if (["received", "threerep"].includes(this.drawOffer)) {
881 if (!confirm(this.st.tr["Accept draw?"])) return;
883 this.drawOffer == "received"
885 : "Three repetitions";
886 this.send("draw", { data: message });
887 this.gameOver("1/2", message);
888 } else if (this.drawOffer == "") {
889 // No effect if drawOffer == "sent"
890 if (this.game.mycolor != this.vr.turn) {
891 alert(this.st.tr["Draw offer only in your turn"]);
894 if (!confirm(this.st.tr["Offer draw?"])) return;
895 this.drawOffer = "sent";
896 this.send("drawoffer");
897 if (this.game.type == "live") {
900 { drawOffer: this.game.mycolor }
902 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
905 addAndGotoLiveGame: function(gameInfo, callback) {
906 const game = Object.assign(
910 // (other) Game infos: constant
911 fenStart: gameInfo.fen,
912 vname: this.game.vname,
914 // Game state (including FEN): will be updated
916 clocks: [-1, -1], //-1 = unstarted
920 GameStorage.add(game, (err) => {
921 // No error expected.
923 if (this.st.settings.sound)
924 new Audio("/sounds/newgame.flac").play().catch(() => {});
925 if (!!callback) callback();
926 this.$router.push("/game/" + gameInfo.id);
930 clickRematch: function() {
931 if (!this.game.mycolor) return; //I'm just spectator
932 if (this.rematchOffer == "received") {
935 id: getRandString(), //ignored if corr
936 fen: V.GenRandInitFen(this.game.randomness),
937 players: this.game.players.reverse(),
939 cadence: this.game.cadence
941 const notifyNewGame = () => {
942 const oppsid = this.getOppsid(); //may be null
943 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
944 // To main Hall if corr game:
945 if (this.game.type == "corr")
946 this.send("newgame", { data: gameInfo, page: "/" });
947 // Also to MyGames page:
948 this.notifyMyGames("newgame", gameInfo);
950 if (this.game.type == "live")
951 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
958 // cid is useful to delete the challenge:
959 data: { gameInfo: gameInfo },
960 success: (response) => {
961 gameInfo.id = response.gameId;
963 this.$router.push("/game/" + response.gameId);
968 } else if (this.rematchOffer == "") {
969 this.rematchOffer = "sent";
970 this.send("rematchoffer", { data: true });
971 if (this.game.type == "live") {
974 { rematchOffer: this.game.mycolor }
976 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
977 } else if (this.rematchOffer == "sent") {
978 // Toggle rematch offer (on --> off)
979 this.rematchOffer = "";
980 this.send("rematchoffer", { data: false });
981 if (this.game.type == "live") {
986 } else this.updateCorrGame({ rematchOffer: 'n' });
989 abortGame: function() {
990 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
992 this.gameOver("?", "Stop");
996 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
998 this.send("resign", { data: this.game.mycolor });
999 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1000 const side = (this.game.mycolor == "w" ? "White" : "Black");
1001 this.gameOver(score, side + " surrender");
1003 loadGame: function(game, callback) {
1004 this.vr = new V(game.fen);
1005 const gtype = this.getGameType(game);
1006 const tc = extractTime(game.cadence);
1007 const myIdx = game.players.findIndex(p => {
1008 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1010 // "mycolor" is undefined for observers
1011 const mycolor = [undefined, "w", "b"][myIdx + 1];
1012 // Live games before 26/03/2020 don't have chat history:
1013 if (!game.chats) game.chats = []; //TODO: remove line
1014 // Sort chat messages from newest to oldest
1015 game.chats.sort((c1, c2) => c2.added - c1.added);
1016 if (gtype == "corr") {
1017 // NOTE: clocks in seconds
1018 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1019 game.clocks = [tc.mainTime, tc.mainTime];
1020 const L = game.moves.length;
1021 if (game.score == "*") {
1024 game.clocks[L % 2] -=
1025 (Date.now() - game.moves[L-1].played) / 1000;
1028 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
1029 // Did a chat message arrive after my last move?
1031 if (L == 1 && myIdx == 0)
1032 dtLastMove = game.moves[0].played;
1035 // It's now white turn
1036 dtLastMove = game.moves[L-1-(1-myIdx)].played;
1039 dtLastMove = game.moves[L-1-myIdx].played;
1042 if (dtLastMove < game.chats[0].added)
1043 document.getElementById("chatBtn").classList.add("somethingnew");
1045 // Now that we used idx and played, re-format moves as for live games
1046 game.moves = game.moves.map(m => m.squares);
1048 if (gtype == "live") {
1050 game.chats.length > 0 &&
1051 (!game.initime || game.initime < game.chats[0].added)
1053 document.getElementById("chatBtn").classList.add("somethingnew");
1055 if (game.clocks[0] < 0) {
1056 // Game is unstarted. clock is ignored until move 2
1057 game.clocks = [tc.mainTime, tc.mainTime];
1059 // I play in this live game
1060 GameStorage.update(game.id, {
1066 // It's my turn: clocks not updated yet
1067 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1070 // TODO: merge next 2 "if" conditions
1071 if (!!game.drawOffer) {
1072 if (game.drawOffer == "t")
1073 // Three repetitions
1074 this.drawOffer = "threerep";
1076 // Draw offered by any of the players:
1077 if (myIdx < 0) this.drawOffer = "received";
1079 // I play in this game:
1081 (game.drawOffer == "w" && myIdx == 0) ||
1082 (game.drawOffer == "b" && myIdx == 1)
1084 this.drawOffer = "sent";
1085 else this.drawOffer = "received";
1089 if (!!game.rematchOffer) {
1090 if (myIdx < 0) this.rematchOffer = "received";
1092 // I play in this game:
1094 (game.rematchOffer == "w" && myIdx == 0) ||
1095 (game.rematchOffer == "b" && myIdx == 1)
1097 this.rematchOffer = "sent";
1098 else this.rematchOffer = "received";
1101 this.repeat = {}; //reset: scan past moves' FEN:
1103 let vr_tmp = new V(game.fenStart);
1105 game.moves.forEach(m => {
1106 playMove(m, vr_tmp);
1107 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1108 this.repeat[fenIdx] = this.repeat[fenIdx]
1109 ? this.repeat[fenIdx] + 1
1112 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1113 this.game = Object.assign(
1114 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1117 increment: tc.increment,
1119 // opponent sid not strictly required (or available), but easier
1120 // at least oppsid or oppid is available anyway:
1121 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1122 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1126 this.$refs["basegame"].re_setVariables(this.game);
1127 if (!this.gameIsLoading) {
1129 this.gotMoveIdx = game.moves.length - 1;
1130 // If we arrive here after 'nextGame' action, the board might be hidden
1131 let boardDiv = document.querySelector(".game");
1132 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1133 boardDiv.style.visibility = "visible";
1135 this.re_setClocks();
1136 this.$nextTick(() => {
1137 this.game.rendered = true;
1138 // Did lastate arrive before game was rendered?
1139 if (this.lastate) this.processLastate();
1141 if (this.lastateAsked) {
1142 this.lastateAsked = false;
1143 this.sendLastate(game.oppsid);
1145 if (this.gameIsLoading) {
1146 this.gameIsLoading = false;
1147 if (this.gotMoveIdx >= game.moves.length)
1148 // Some moves arrived meanwhile...
1149 this.askGameAgain();
1151 if (!!callback) callback();
1153 loadVariantThenGame: async function(game, callback) {
1154 await import("@/variants/" + game.vname + ".js")
1155 .then((vModule) => {
1156 window.V = vModule[game.vname + "Rules"];
1157 this.loadGame(game, callback);
1160 // 3 cases for loading a game:
1161 // - from indexedDB (running or completed live game I play)
1162 // - from server (one correspondance game I play[ed] or not)
1163 // - from remote peer (one live game I don't play, finished or not)
1164 fetchGame: function(callback) {
1165 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1166 // corr games identifiers are integers
1171 data: { gid: this.gameRef },
1173 res.game.moves.forEach(m => {
1174 m.squares = JSON.parse(m.squares);
1181 // Local game (or live remote)
1182 GameStorage.get(this.gameRef, callback);
1184 re_setClocks: function() {
1185 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1186 if (this.game.moves.length < 2 || this.game.score != "*") {
1187 // 1st move not completed yet, or game over: freeze time
1190 const currentTurn = this.vr.turn;
1191 const currentMovesCount = this.game.moves.length;
1192 const colorIdx = ["w", "b"].indexOf(currentTurn);
1193 this.clockUpdate = setInterval(
1196 this.game.clocks[colorIdx] < 0 ||
1197 this.game.moves.length > currentMovesCount ||
1198 this.game.score != "*"
1200 clearInterval(this.clockUpdate);
1201 this.clockUpdate = null;
1202 if (this.game.clocks[colorIdx] < 0)
1204 currentTurn == "w" ? "0-1" : "1-0",
1211 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1218 // Update variables and storage after a move:
1219 processMove: function(move, data) {
1220 if (!data) data = {};
1221 const moveCol = this.vr.turn;
1222 const colorIdx = ["w", "b"].indexOf(moveCol);
1223 const nextIdx = 1 - colorIdx;
1224 const doProcessMove = () => {
1225 const origMovescount = this.game.moves.length;
1226 // The move is (about to be) played: stop clock
1227 clearInterval(this.clockUpdate);
1228 this.clockUpdate = null;
1229 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1230 if (this.drawOffer == "received")
1232 this.drawOffer = "";
1233 if (this.game.type == "live" && origMovescount >= 2) {
1234 this.game.clocks[colorIdx] += this.game.increment;
1235 // For a correct display in casqe of disconnected opponent:
1239 ppt(this.game.clocks[colorIdx]).split(':')
1241 GameStorage.update(this.gameRef, {
1242 // It's not my turn anymore:
1247 // Update current game object:
1248 playMove(move, this.vr);
1250 // Received move, score is computed in BaseGame, but maybe not yet.
1251 // ==> Compute it here, although this is redundant (TODO)
1252 data.score = this.vr.getCurrentScore();
1253 if (data.score != "*") this.gameOver(data.score);
1254 this.game.moves.push(move);
1255 this.game.fen = this.vr.getFen();
1256 if (this.game.type == "corr") {
1257 // In corr games, just reset clock to mainTime:
1258 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1260 // If repetition detected, consider that a draw offer was received:
1261 const fenObj = this.vr.getFenForRepeat();
1262 this.repeat[fenObj] =
1263 !!this.repeat[fenObj]
1264 ? this.repeat[fenObj] + 1
1266 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1267 else if (this.drawOffer == "threerep") this.drawOffer = "";
1268 if (!!this.game.mycolor && !data.receiveMyMove) {
1269 // NOTE: 'var' to see that variable outside this block
1270 var filtered_move = getFilteredMove(move);
1272 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1273 // Notify turn on MyGames page:
1282 // Since corr games are stored at only one location, update should be
1283 // done only by one player for each move:
1285 this.game.type == "live" &&
1286 !!this.game.mycolor &&
1287 moveCol != this.game.mycolor &&
1288 this.game.moves.length >= 2
1290 // Receive a move: update initime
1291 this.game.initime = Date.now();
1292 GameStorage.update(this.gameRef, {
1293 // It's my turn now!
1294 initime: this.game.initime
1298 !!this.game.mycolor &&
1299 !data.receiveMyMove &&
1300 (this.game.type == "live" || moveCol == this.game.mycolor)
1303 switch (this.drawOffer) {
1308 drawCode = this.game.mycolor;
1311 drawCode = V.GetOppCol(this.game.mycolor);
1314 if (this.game.type == "corr") {
1315 // corr: only move, fen and score
1316 this.updateCorrGame({
1319 squares: filtered_move,
1322 // Code "n" for "None" to force reset (otherwise it's ignored)
1323 drawOffer: drawCode || "n"
1327 const updateStorage = () => {
1328 GameStorage.update(this.gameRef, {
1330 move: filtered_move,
1331 moveIdx: origMovescount,
1332 clocks: this.game.clocks,
1336 // The active tab can update storage immediately
1337 if (this.focus) updateStorage();
1338 // Small random delay otherwise
1339 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1342 // Send move ("newmove" event) to people in the room (if our turn)
1343 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1345 move: filtered_move,
1346 index: origMovescount,
1347 // color is required to check if this is my move
1348 // (if several tabs opened)
1350 cancelDrawOffer: this.drawOffer == ""
1352 if (this.game.type == "live")
1353 sendMove["clock"] = this.game.clocks[colorIdx];
1354 // (Live) Clocks will re-start when the opponent pingback arrive
1355 this.opponentGotMove = false;
1356 this.send("newmove", {data: sendMove});
1357 // If the opponent doesn't reply gotmove soon enough, re-send move:
1358 // Do this at most 2 times, because mpore would mean network issues,
1359 // opponent would then be expected to disconnect/reconnect.
1361 const currentUrl = document.location.href;
1362 this.retrySendmove = setInterval(
1366 this.opponentGotMove ||
1367 document.location.href != currentUrl //page change
1369 clearInterval(this.retrySendmove);
1372 const oppsid = this.getOppsid();
1374 // Opponent is disconnected: he'll ask last state
1375 clearInterval(this.retrySendmove);
1377 this.send("newmove", { data: sendMove, target: oppsid });
1385 // Not my move or I'm an observer: just start other player's clock
1386 this.re_setClocks();
1389 this.game.type == "corr" &&
1390 moveCol == this.game.mycolor &&
1393 let boardDiv = document.querySelector(".game");
1394 const afterSetScore = () => {
1396 if (this.st.settings.gotonext && this.nextIds.length > 0)
1397 this.showNextGame();
1399 // The board might have been hidden:
1400 if (boardDiv.style.visibility == "hidden")
1401 boardDiv.style.visibility = "visible";
1402 if (data.score == "*") this.re_setClocks();
1405 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1406 // We may play several moves in a row: in case of, remove listener:
1407 let elClone = el.cloneNode(true);
1408 el.parentNode.replaceChild(elClone, el);
1409 elClone.addEventListener(
1412 document.getElementById("modalConfirm").checked = false;
1413 if (!!data.score && data.score != "*")
1415 this.gameOver(data.score, null, afterSetScore);
1416 else afterSetScore();
1419 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1420 V.PlayOnBoard(this.vr.board, move);
1421 const position = this.vr.getBaseFen();
1422 V.UndoOnBoard(this.vr.board, move);
1423 if (["all","byrow"].includes(V.ShowMoves)) {
1424 this.curDiag = getDiagram({
1426 orientation: V.CanFlip ? this.game.mycolor : "w"
1428 document.querySelector("#confirmDiv > .card").style.width =
1429 boardDiv.offsetWidth + "px";
1431 // Incomplete information: just ask confirmation
1432 // Hide the board, because otherwise it could reveal infos
1433 boardDiv.style.visibility = "hidden";
1434 this.moveNotation = getFullNotation(move);
1436 document.getElementById("modalConfirm").checked = true;
1440 if (!!data.score && data.score != "*")
1441 this.gameOver(data.score, null, doProcessMove);
1442 else doProcessMove();
1445 cancelMove: function() {
1446 let boardDiv = document.querySelector(".game");
1447 if (boardDiv.style.visibility == "hidden")
1448 boardDiv.style.visibility = "visible";
1449 document.getElementById("modalConfirm").checked = false;
1450 this.$refs["basegame"].cancelLastMove();
1452 // In corr games, callback to change page only after score is set:
1453 gameOver: function(score, scoreMsg, callback) {
1454 this.game.score = score;
1455 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1456 this.game.scoreMsg = scoreMsg;
1457 this.$set(this.game, "scoreMsg", scoreMsg);
1458 const myIdx = this.game.players.findIndex(p => {
1459 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1462 // OK, I play in this game
1467 if (this.game.type == "live") {
1468 GameStorage.update(this.gameRef, scoreObj);
1469 // Notify myself locally if I'm elsewhere:
1473 { body: score + " : " + scoreMsg }
1476 if (!!callback) callback();
1478 else this.updateCorrGame(scoreObj, callback);
1479 // Notify the score to main Hall.
1480 // TODO: only one player (currently double send)
1481 this.send("result", { gid: this.game.id, score: score });
1482 // Also to MyGames page (TODO: doubled as well...)
1491 else if (!!callback) callback();
1497 <style lang="sass" scoped>
1503 background-color: lightgreen
1515 @media screen and (min-width: 768px)
1518 @media screen and (max-width: 767px)
1523 display: inline-block
1527 display: inline-block
1529 display: inline-flex
1533 @media screen and (max-width: 767px)
1536 @media screen and (max-width: 767px)
1539 @media screen and (min-width: 768px)
1551 background-color: #edda99
1553 display: inline-block
1562 display: inline-block
1575 animation: blink-animation 2s steps(3, start) infinite
1576 @keyframes blink-animation
1581 display: inline-block
1593 .draw-sent, .draw-sent:hover
1594 background-color: lightyellow
1596 .draw-received, .draw-received:hover
1597 background-color: lightgreen
1599 .draw-threerep, .draw-threerep:hover
1600 background-color: #e4d1fc
1602 .rematch-sent, .rematch-sent:hover
1603 background-color: lightyellow
1605 .rematch-received, .rematch-received:hover
1606 background-color: lightgreen
1609 background-color: #c5fefe
1622 background-color: lightgreen
1624 background-color: red