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 { ajax } from "@/utils/ajax";
135 import { extractTime } from "@/utils/timeControl";
136 import { getRandString } from "@/utils/alea";
137 import { getScoreMessage } from "@/utils/scoring";
138 import { getFullNotation } from "@/utils/notation";
139 import { getDiagram } from "@/utils/printDiagram";
140 import { processModalClick } from "@/utils/modalClick";
141 import { playMove, getFilteredMove } from "@/utils/playUndo";
142 import { ArrayFun } from "@/utils/array";
143 import params from "@/parameters";
153 // gameRef can point to a corr game, local game or remote live game
156 game: {}, //passed to BaseGame
157 // virtualClocks will be initialized from true game.clocks
159 vr: null, //"variant rules" object initialized from FEN
164 people: {}, //players + observers
165 lastate: undefined, //used if opponent send lastate before game is ready
166 repeat: {}, //detect position repetition
167 curDiag: "", //for corr moves confirmation
169 roomInitialized: false,
170 // If newmove has wrong index: ask fullgame again:
172 gameIsLoading: false,
173 // If asklastate got no reply, ask again:
175 gotMoveIdx: -1, //last move index received
176 // If newmove got no pingback, send again:
177 opponentGotMove: false,
179 socketCloseListener: 0,
180 // Incomplete info games: show move played
182 // Intervals from setInterval():
186 // Related to (killing of) self multi-connects:
192 $route: function(to, from) {
193 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
195 this.cleanBeforeDestroy();
196 else if (from.params["id"] != to.params["id"]) {
197 // Change everything:
198 this.cleanBeforeDestroy();
199 let boardDiv = document.querySelector(".game");
201 // In case of incomplete information variant:
202 boardDiv.style.visibility = "hidden";
206 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
209 // NOTE: some redundant code with Hall.vue (mostly related to people array)
210 created: function() {
213 mounted: function() {
214 ["chatWrap", "infoDiv"].forEach(eltName => {
215 document.getElementById(eltName)
216 .addEventListener("click", processModalClick);
218 if ("ontouchstart" in window) {
219 // Disable tooltips on smartphones:
220 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
221 elt.classList.remove("tooltip");
225 beforeDestroy: function() {
226 this.cleanBeforeDestroy();
229 cleanBeforeDestroy: function() {
230 clearInterval(this.socketCloseListener);
231 document.removeEventListener('visibilitychange', this.visibilityChange);
232 if (!!this.askLastate) clearInterval(this.askLastate);
233 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
234 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
235 this.conn.removeEventListener("message", this.socketMessageListener);
236 this.send("disconnect");
239 visibilityChange: function() {
240 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
242 document.visibilityState == "visible"
247 participateInChat: function(p) {
248 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
250 someAnonymousPresent: function() {
252 Object.values(this.people).some(p =>
253 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
257 atCreation: function() {
258 document.addEventListener('visibilitychange', this.visibilityChange);
259 // 0] (Re)Set variables
260 this.gameRef = this.$route.params["id"];
261 // next = next corr games IDs to navigate faster (if applicable)
262 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
263 // Always add myself to players' list
264 const my = this.st.user;
265 const tmpId = getRandString();
273 tmpId: { focus: true }
278 players: [{ name: "" }, { name: "" }],
282 let chatComp = this.$refs["chatcomp"];
283 if (!!chatComp) chatComp.chats = [];
284 this.virtualClocks = [[0,0], [0,0]];
287 this.lastateAsked = false;
288 this.rematchOffer = "";
289 this.lastate = undefined;
290 this.roomInitialized = false;
291 this.askGameTime = 0;
292 this.gameIsLoading = false;
293 this.gotLastate = false;
294 this.gotMoveIdx = -1;
295 this.opponentGotMove = false;
296 this.askLastate = null;
297 this.retrySendmove = null;
298 this.clockUpdate = null;
299 this.newConnect = {};
301 // 1] Initialize connection
302 this.connexionString =
304 "/?sid=" + this.st.user.sid +
305 "&id=" + this.st.user.id +
308 // Discard potential "/?next=[...]" for page indication:
309 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
310 this.conn = new WebSocket(this.connexionString);
311 this.conn.addEventListener("message", this.socketMessageListener);
312 this.socketCloseListener = setInterval(
314 if (this.conn.readyState == 3) {
315 this.conn.removeEventListener("message", this.socketMessageListener);
316 this.conn = new WebSocket(this.connexionString);
317 this.conn.addEventListener("message", this.socketMessageListener);
322 // Socket init required before loading remote game:
323 const socketInit = callback => {
324 if (this.conn.readyState == 1)
328 // Socket not ready yet (initial loading)
329 // NOTE: first arg is Websocket object, unused here:
330 this.conn.onopen = () => callback();
332 this.fetchGame((game) => {
334 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
336 // Live game stored remotely: need socket to retrieve it
337 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
338 // --> It will be given when receiving "fullgame" socket event.
339 socketInit(() => { this.send("askfullgame"); });
342 roomInit: function() {
343 if (!this.roomInitialized) {
344 // Notify the room only now that I connected, because
345 // messages might be lost otherwise (if game loading is slow)
346 this.send("connect");
347 this.send("pollclients");
348 // We may ask fullgame several times if some moves are lost,
349 // but room should be init only once:
350 this.roomInitialized = true;
353 send: function(code, obj) {
355 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
357 isConnected: function(index) {
358 const player = this.game.players[index];
359 // Is it me ? In this case no need to bother with focus
360 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
361 // Still have to check for name (because of potential multi-accounts
362 // on same browser, although this should be rare...)
363 return (!this.st.user.name || this.st.user.name == player.name);
364 // Try to find a match in people:
368 Object.keys(this.people).some(sid => {
371 Object.values(this.people[sid].tmpIds).some(v => v.focus)
378 Object.values(this.people).some(p => {
381 Object.values(p.tmpIds).some(v => v.focus)
387 getOppsid: function() {
388 let oppsid = this.game.oppsid;
390 oppsid = Object.keys(this.people).find(
391 sid => this.people[sid].id == this.game.oppid
394 // oppsid is useful only if opponent is online:
395 if (!!oppsid && !!this.people[oppsid]) return oppsid;
398 toggleChat: function() {
399 if (document.getElementById("modalChat").checked)
401 document.getElementById("inputChat").focus();
402 // TODO: next line is only required when exiting chat,
403 // but the event for now isn't well detected.
404 document.getElementById("chatBtn").classList.remove("somethingnew");
406 processChat: function(chat) {
407 this.send("newchat", { data: chat });
408 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
409 if (this.game.type == "corr" && this.st.user.id > 0)
410 this.updateCorrGame({ chat: chat });
412 clearChat: function() {
413 // Nothing more to do if game is live (chats not recorded)
414 if (this.game.type == "corr") {
415 if (!!this.game.mycolor) {
419 { data: { gid: this.game.id } }
422 this.$set(this.game, "chats", []);
425 getGameType: function(game) {
426 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
428 // Notify something after a new move (to opponent and me on MyGames page)
429 notifyMyGames: function(thing, data) {
434 targets: this.game.players.map(p => {
435 return { sid: p.sid, id: p.id };
440 showNextGame: function() {
441 // Did I play in current game? If not, add it to nextIds list
442 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
443 this.nextIds.unshift(this.game.id);
444 const nextGid = this.nextIds.pop();
446 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
448 askGameAgain: function() {
449 this.gameIsLoading = true;
450 const currentUrl = document.location.href;
451 const doAskGame = () => {
452 if (document.location.href != currentUrl) return; //page change
453 this.fetchGame((game) => {
455 // This is my game: just reload.
458 // Just ask fullgame again (once!), this is much simpler.
459 // If this fails, the user could just reload page :/
460 this.send("askfullgame");
463 // Delay of at least 2s between two game requests
464 const now = Date.now();
465 const delay = Math.max(2000 - (now - this.askGameTime), 0);
466 this.askGameTime = now;
467 setTimeout(doAskGame, delay);
469 socketMessageListener: function(msg) {
470 if (!this.conn) return;
471 const data = JSON.parse(msg.data);
474 // TODO: shuffling and random filtering on server,
475 // if the room is really crowded.
476 Object.keys(data.sockIds).forEach(sid => {
477 if (sid != this.st.user.sid) {
478 this.send("askidentity", { target: sid });
479 this.people[sid] = { tmpIds: data.sockIds[sid] };
481 // Complete my tmpIds:
482 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
487 if (!this.people[data.from[0]]) {
488 // focus depends on the tmpId (e.g. tab)
494 [data.from[1]]: { focus: true }
498 this.newConnect[data.from] = true; //for self multi-connects tests
499 this.send("askidentity", { target: data.from[0] });
501 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
502 this.$forceUpdate(); //TODO: shouldn't be required
506 if (!this.people[data.from[0]]) return;
507 delete this.people[data.from[0]].tmpIds[data.from[1]];
508 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
509 this.$delete(this.people, data.from[0]);
510 else this.$forceUpdate(); //TODO: shouldn't be required
513 let player = this.people[data.from[0]];
515 player.tmpIds[data.from[1]].focus = true;
516 this.$forceUpdate(); //TODO: shouldn't be required
521 let player = this.people[data.from[0]];
523 player.tmpIds[data.from[1]].focus = false;
524 this.$forceUpdate(); //TODO: shouldn't be required
529 // I logged in elsewhere:
530 this.conn.removeEventListener("message", this.socketMessageListener);
531 this.conn.removeEventListener("close", this.socketCloseListener);
533 alert(this.st.tr["New connexion detected: tab now offline"]);
535 case "askidentity": {
536 // Request for identification
538 // Decompose to avoid revealing email
539 name: this.st.user.name,
540 sid: this.st.user.sid,
543 this.send("identity", { data: me, target: data.from });
547 const user = data.data;
548 let player = this.people[user.sid];
549 // player.tmpIds is already set
550 player.name = user.name;
552 this.$forceUpdate(); //TODO: shouldn't be required
553 // If I multi-connect, kill current connexion if no mark (I'm older)
554 if (this.newConnect[user.sid]) {
557 user.id == this.st.user.id &&
558 user.sid != this.st.user.sid &&
559 !this.killed[this.st.user.sid]
561 this.send("killme", { sid: this.st.user.sid });
562 this.killed[this.st.user.sid] = true;
564 delete this.newConnect[user.sid];
566 if (!this.killed[this.st.user.sid]) {
567 // Ask potentially missed last state, if opponent and I play
570 !!this.game.mycolor &&
571 this.game.type == "live" &&
572 this.game.score == "*" &&
573 this.game.players.some(p => p.sid == user.sid)
575 this.send("asklastate", { target: user.sid });
577 this.askLastate = setInterval(
579 // Ask at most 3 times:
580 // if no reply after that there should be a network issue.
584 !!this.people[user.sid]
586 this.send("asklastate", { target: user.sid });
589 clearInterval(this.askLastate);
599 // Send current (live) game if not asked by any of the players
601 this.game.type == "live" &&
602 this.game.players.every(p => p.sid != data.from[0])
607 players: this.game.players,
609 cadence: this.game.cadence,
610 score: this.game.score
612 this.send("game", { data: myGame, target: data.from });
616 const gameToSend = Object.keys(this.game)
619 "id","fen","players","vid","cadence","fenStart","vname",
620 "moves","clocks","score","drawOffer","rematchOffer"
624 obj[k] = this.game[k];
629 this.send("fullgame", { data: gameToSend, target: data.from });
632 if (!!data.data.empty) {
633 alert(this.st.tr["The game should be in another tab"]);
637 // Callback "roomInit" to poll clients only after game is loaded
638 this.loadVariantThenGame(data.data, this.roomInit);
641 // Sending informative last state if I played a move or score != "*"
642 // If the game or moves aren't loaded yet, delay the sending:
643 // TODO: since socket init after game load, the game is supposedly ready
644 if (!this.game || !this.game.moves) this.lastateAsked = true;
645 else this.sendLastate(data.from);
648 // Got opponent infos about last move
649 this.gotLastate = true;
650 this.lastate = data.data;
651 if (this.game.rendered)
652 // Game is rendered (Board component)
653 this.processLastate();
654 // Else: will be processed when game is ready
658 const movePlus = data.data;
659 const movesCount = this.game.moves.length;
660 if (movePlus.index > movesCount) {
661 // This can only happen if I'm an observer and missed a move.
662 if (this.gotMoveIdx < movePlus.index)
663 this.gotMoveIdx = movePlus.index;
664 if (!this.gameIsLoading) this.askGameAgain();
668 movePlus.index < movesCount ||
669 this.gotMoveIdx >= movePlus.index
671 // Opponent re-send but we already have the move:
672 // (maybe he didn't receive our pingback...)
673 this.send("gotmove", {data: movePlus.index, target: data.from});
675 this.gotMoveIdx = movePlus.index;
676 const receiveMyMove = (movePlus.color == this.game.mycolor);
677 if (!receiveMyMove && !!this.game.mycolor)
678 // Notify opponent that I got the move:
679 this.send("gotmove", {data: movePlus.index, target: data.from});
680 if (movePlus.cancelDrawOffer) {
681 // Opponent refuses draw
683 // NOTE for corr games: drawOffer reset by player in turn
685 this.game.type == "live" &&
686 !!this.game.mycolor &&
689 GameStorage.update(this.gameRef, { drawOffer: "" });
692 this.$refs["basegame"].play(movePlus.move, "received", null, true);
693 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
694 this.game.clocks[moveColIdx] = movePlus.clock;
697 { receiveMyMove: receiveMyMove }
704 this.opponentGotMove = true;
705 // Now his clock starts running on my side:
706 const oppIdx = ['w','b'].indexOf(this.vr.turn);
707 // NOTE: next line to avoid multi-resetClocks when several tabs
708 // on same game, resulting in a faster countdown.
709 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
714 const score = (data.data == "b" ? "1-0" : "0-1");
715 const side = (data.data == "w" ? "White" : "Black");
716 this.gameOver(score, side + " surrender");
719 this.gameOver("?", "Stop");
722 this.gameOver("1/2", data.data);
725 // NOTE: observers don't know who offered draw
726 this.drawOffer = "received";
727 if (this.game.type == "live") {
730 { drawOffer: V.GetOppCol(this.game.mycolor) }
735 // NOTE: observers don't know who offered rematch
736 this.rematchOffer = data.data ? "received" : "";
737 if (this.game.type == "live") {
740 { rematchOffer: V.GetOppCol(this.game.mycolor) }
745 // A game started, redirect if I'm playing in
746 const gameInfo = data.data;
747 const gameType = this.getGameType(gameInfo);
749 gameType == "live" &&
750 gameInfo.players.some(p => p.sid == this.st.user.sid)
752 this.addAndGotoLiveGame(gameInfo);
754 gameType == "corr" &&
755 gameInfo.players.some(p => p.id == this.st.user.id)
757 this.$router.push("/game/" + gameInfo.id);
759 this.rematchId = gameInfo.id;
760 document.getElementById("modalInfo").checked = true;
765 this.$refs["chatcomp"].newChat(data.data);
766 if (!document.getElementById("modalChat").checked)
767 document.getElementById("chatBtn").classList.add("somethingnew");
771 updateCorrGame: function(obj, callback) {
781 if (!!callback) callback();
786 sendLastate: function(target) {
787 // Send our "last state" informations to opponent
788 const L = this.game.moves.length;
789 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
792 (L > 0 && this.vr.turn != this.game.mycolor)
793 ? this.game.moves[L - 1]
795 clock: this.game.clocks[myIdx],
796 // Since we played a move (or abort or resign),
797 // only drawOffer=="sent" is possible
798 drawSent: this.drawOffer == "sent",
799 rematchSent: this.rematchOffer == "sent",
800 score: this.game.score != "*" ? this.game.score : undefined,
801 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
804 this.send("lastate", { data: myLastate, target: target });
806 // lastate was received, but maybe game wasn't ready yet:
807 processLastate: function() {
808 const data = this.lastate;
809 this.lastate = undefined; //security...
810 const L = this.game.moves.length;
811 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
812 this.game.clocks[oppIdx] = data.clock;
813 if (data.movesCount > L) {
814 // Just got last move from him
815 this.$refs["basegame"].play(data.lastMove, "received", null, true);
816 this.processMove(data.lastMove);
818 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
821 if (data.drawSent) this.drawOffer = "received";
822 if (data.rematchSent) this.rematchOffer = "received";
825 if (this.game.score == "*")
826 this.gameOver(data.score, data.scoreMsg);
829 clickDraw: function() {
830 if (!this.game.mycolor) return; //I'm just spectator
831 if (["received", "threerep"].includes(this.drawOffer)) {
832 if (!confirm(this.st.tr["Accept draw?"])) return;
834 this.drawOffer == "received"
836 : "Three repetitions";
837 this.send("draw", { data: message });
838 this.gameOver("1/2", message);
839 } else if (this.drawOffer == "") {
840 // No effect if drawOffer == "sent"
841 if (this.game.mycolor != this.vr.turn) {
842 alert(this.st.tr["Draw offer only in your turn"]);
845 if (!confirm(this.st.tr["Offer draw?"])) return;
846 this.drawOffer = "sent";
847 this.send("drawoffer");
848 if (this.game.type == "live") {
851 { drawOffer: this.game.mycolor }
853 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
856 addAndGotoLiveGame: function(gameInfo, callback) {
857 const game = Object.assign(
861 // (other) Game infos: constant
862 fenStart: gameInfo.fen,
863 vname: this.game.vname,
865 // Game state (including FEN): will be updated
867 clocks: [-1, -1], //-1 = unstarted
871 GameStorage.add(game, (err) => {
872 // No error expected.
874 if (this.st.settings.sound)
875 new Audio("/sounds/newgame.flac").play().catch(() => {});
876 if (!!callback) callback();
877 this.$router.push("/game/" + gameInfo.id);
881 clickRematch: function() {
882 if (!this.game.mycolor) return; //I'm just spectator
883 if (this.rematchOffer == "received") {
886 id: getRandString(), //ignored if corr
887 fen: V.GenRandInitFen(this.game.randomness),
888 players: this.game.players.reverse(),
890 cadence: this.game.cadence
892 const notifyNewGame = () => {
893 const oppsid = this.getOppsid(); //may be null
894 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
895 // To main Hall if corr game:
896 if (this.game.type == "corr")
897 this.send("newgame", { data: gameInfo, page: "/" });
898 // Also to MyGames page:
899 this.notifyMyGames("newgame", gameInfo);
901 if (this.game.type == "live")
902 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
909 // cid is useful to delete the challenge:
910 data: { gameInfo: gameInfo },
911 success: (response) => {
912 gameInfo.id = response.gameId;
914 this.$router.push("/game/" + response.gameId);
919 } else if (this.rematchOffer == "") {
920 this.rematchOffer = "sent";
921 this.send("rematchoffer", { data: true });
922 if (this.game.type == "live") {
925 { rematchOffer: this.game.mycolor }
927 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
928 } else if (this.rematchOffer == "sent") {
929 // Toggle rematch offer (on --> off)
930 this.rematchOffer = "";
931 this.send("rematchoffer", { data: false });
932 if (this.game.type == "live") {
937 } else this.updateCorrGame({ rematchOffer: 'n' });
940 abortGame: function() {
941 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
942 this.gameOver("?", "Stop");
946 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
948 this.send("resign", { data: this.game.mycolor });
949 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
950 const side = (this.game.mycolor == "w" ? "White" : "Black");
951 this.gameOver(score, side + " surrender");
953 loadGame: function(game, callback) {
954 this.vr = new V(game.fen);
955 const gtype = this.getGameType(game);
956 const tc = extractTime(game.cadence);
957 const myIdx = game.players.findIndex(p => {
958 return p.sid == this.st.user.sid || p.id == this.st.user.id;
960 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
961 if (!game.chats) game.chats = []; //live games don't have chat history
962 if (gtype == "corr") {
963 // NOTE: clocks in seconds
964 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
965 game.clocks = [tc.mainTime, tc.mainTime];
966 const L = game.moves.length;
967 if (game.score == "*") {
970 game.clocks[L % 2] -=
971 (Date.now() - game.moves[L-1].played) / 1000;
974 // Sort chat messages from newest to oldest
975 game.chats.sort((c1, c2) => {
976 return c2.added - c1.added;
978 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
979 // Did a chat message arrive after my last move?
981 if (L == 1 && myIdx == 0)
982 dtLastMove = game.moves[0].played;
985 // It's now white turn
986 dtLastMove = game.moves[L-1-(1-myIdx)].played;
989 dtLastMove = game.moves[L-1-myIdx].played;
992 if (dtLastMove < game.chats[0].added)
993 document.getElementById("chatBtn").classList.add("somethingnew");
995 // Now that we used idx and played, re-format moves as for live games
996 game.moves = game.moves.map(m => m.squares);
998 if (gtype == "live") {
999 if (game.clocks[0] < 0) {
1000 // Game is unstarted. clock is ignored until move 2
1001 game.clocks = [tc.mainTime, tc.mainTime];
1003 // I play in this live game
1004 GameStorage.update(game.id, {
1010 // It's my turn: clocks not updated yet
1011 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1014 // TODO: merge next 2 "if" conditions
1015 if (!!game.drawOffer) {
1016 if (game.drawOffer == "t")
1017 // Three repetitions
1018 this.drawOffer = "threerep";
1020 // Draw offered by any of the players:
1021 if (myIdx < 0) this.drawOffer = "received";
1023 // I play in this game:
1025 (game.drawOffer == "w" && myIdx == 0) ||
1026 (game.drawOffer == "b" && myIdx == 1)
1028 this.drawOffer = "sent";
1029 else this.drawOffer = "received";
1033 if (!!game.rematchOffer) {
1034 if (myIdx < 0) this.rematchOffer = "received";
1036 // I play in this game:
1038 (game.rematchOffer == "w" && myIdx == 0) ||
1039 (game.rematchOffer == "b" && myIdx == 1)
1041 this.rematchOffer = "sent";
1042 else this.rematchOffer = "received";
1045 this.repeat = {}; //reset: scan past moves' FEN:
1047 let vr_tmp = new V(game.fenStart);
1049 game.moves.forEach(m => {
1050 playMove(m, vr_tmp);
1051 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1052 this.repeat[fenIdx] = this.repeat[fenIdx]
1053 ? this.repeat[fenIdx] + 1
1056 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1057 this.game = Object.assign(
1058 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1061 increment: tc.increment,
1063 // opponent sid not strictly required (or available), but easier
1064 // at least oppsid or oppid is available anyway:
1065 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1066 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1070 this.$refs["basegame"].re_setVariables(this.game);
1071 if (!this.gameIsLoading) {
1073 this.gotMoveIdx = game.moves.length - 1;
1074 // If we arrive here after 'nextGame' action, the board might be hidden
1075 let boardDiv = document.querySelector(".game");
1076 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1077 boardDiv.style.visibility = "visible";
1079 this.re_setClocks();
1080 this.$nextTick(() => {
1081 this.game.rendered = true;
1082 // Did lastate arrive before game was rendered?
1083 if (this.lastate) this.processLastate();
1085 if (this.lastateAsked) {
1086 this.lastateAsked = false;
1087 this.sendLastate(game.oppsid);
1089 if (this.gameIsLoading) {
1090 this.gameIsLoading = false;
1091 if (this.gotMoveIdx >= game.moves.length)
1092 // Some moves arrived meanwhile...
1093 this.askGameAgain();
1095 if (!!callback) callback();
1097 loadVariantThenGame: async function(game, callback) {
1098 await import("@/variants/" + game.vname + ".js")
1099 .then((vModule) => {
1100 window.V = vModule[game.vname + "Rules"];
1101 this.loadGame(game, callback);
1104 // 3 cases for loading a game:
1105 // - from indexedDB (running or completed live game I play)
1106 // - from server (one correspondance game I play[ed] or not)
1107 // - from remote peer (one live game I don't play, finished or not)
1108 fetchGame: function(callback) {
1109 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1110 // corr games identifiers are integers
1115 data: { gid: this.gameRef },
1117 res.game.moves.forEach(m => {
1118 m.squares = JSON.parse(m.squares);
1125 // Local game (or live remote)
1126 GameStorage.get(this.gameRef, callback);
1128 re_setClocks: function() {
1129 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1130 if (this.game.moves.length < 2 || this.game.score != "*") {
1131 // 1st move not completed yet, or game over: freeze time
1134 const currentTurn = this.vr.turn;
1135 const currentMovesCount = this.game.moves.length;
1136 const colorIdx = ["w", "b"].indexOf(currentTurn);
1137 this.clockUpdate = setInterval(
1140 this.game.clocks[colorIdx] < 0 ||
1141 this.game.moves.length > currentMovesCount ||
1142 this.game.score != "*"
1144 clearInterval(this.clockUpdate);
1145 this.clockUpdate = null;
1146 if (this.game.clocks[colorIdx] < 0)
1148 currentTurn == "w" ? "0-1" : "1-0",
1155 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1162 // Update variables and storage after a move:
1163 processMove: function(move, data) {
1164 if (!data) data = {};
1165 const moveCol = this.vr.turn;
1166 const colorIdx = ["w", "b"].indexOf(moveCol);
1167 const nextIdx = 1 - colorIdx;
1168 const doProcessMove = () => {
1169 const origMovescount = this.game.moves.length;
1170 // The move is (about to be) played: stop clock
1171 clearInterval(this.clockUpdate);
1172 this.clockUpdate = null;
1173 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1174 if (this.drawOffer == "received")
1176 this.drawOffer = "";
1177 if (this.game.type == "live" && origMovescount >= 2) {
1178 this.game.clocks[colorIdx] += this.game.increment;
1179 // For a correct display in casqe of disconnected opponent:
1183 ppt(this.game.clocks[colorIdx]).split(':')
1185 GameStorage.update(this.gameRef, {
1186 // It's not my turn anymore:
1191 // Update current game object:
1192 playMove(move, this.vr);
1194 // Received move, score is computed in BaseGame, but maybe not yet.
1195 // ==> Compute it here, although this is redundant (TODO)
1196 data.score = this.vr.getCurrentScore();
1197 if (data.score != "*") this.gameOver(data.score);
1198 this.game.moves.push(move);
1199 this.game.fen = this.vr.getFen();
1200 if (this.game.type == "corr") {
1201 // In corr games, just reset clock to mainTime:
1202 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1204 // If repetition detected, consider that a draw offer was received:
1205 const fenObj = this.vr.getFenForRepeat();
1206 this.repeat[fenObj] =
1207 !!this.repeat[fenObj]
1208 ? this.repeat[fenObj] + 1
1210 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1211 else if (this.drawOffer == "threerep") this.drawOffer = "";
1212 if (!!this.game.mycolor && !data.receiveMyMove) {
1213 // NOTE: 'var' to see that variable outside this block
1214 var filtered_move = getFilteredMove(move);
1216 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1217 // Notify turn on MyGames page:
1226 // Since corr games are stored at only one location, update should be
1227 // done only by one player for each move:
1229 this.game.type == "live" &&
1230 !!this.game.mycolor &&
1231 moveCol != this.game.mycolor &&
1232 this.game.moves.length >= 2
1234 // Receive a move: update initime
1235 this.game.initime = Date.now();
1236 GameStorage.update(this.gameRef, {
1237 // It's my turn now!
1238 initime: this.game.initime
1242 !!this.game.mycolor &&
1243 !data.receiveMyMove &&
1244 (this.game.type == "live" || moveCol == this.game.mycolor)
1247 switch (this.drawOffer) {
1252 drawCode = this.game.mycolor;
1255 drawCode = V.GetOppCol(this.game.mycolor);
1258 if (this.game.type == "corr") {
1259 // corr: only move, fen and score
1260 this.updateCorrGame({
1263 squares: filtered_move,
1266 // Code "n" for "None" to force reset (otherwise it's ignored)
1267 drawOffer: drawCode || "n"
1271 const updateStorage = () => {
1272 GameStorage.update(this.gameRef, {
1274 move: filtered_move,
1275 moveIdx: origMovescount,
1276 clocks: this.game.clocks,
1280 // The active tab can update storage immediately
1281 if (!document.hidden) updateStorage();
1282 // Small random delay otherwise
1283 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1286 // Send move ("newmove" event) to people in the room (if our turn)
1287 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1289 move: filtered_move,
1290 index: origMovescount,
1291 // color is required to check if this is my move (if several tabs opened)
1293 cancelDrawOffer: this.drawOffer == ""
1295 if (this.game.type == "live")
1296 sendMove["clock"] = this.game.clocks[colorIdx];
1297 // (Live) Clocks will re-start when the opponent pingback arrive
1298 this.opponentGotMove = false;
1299 this.send("newmove", {data: sendMove});
1300 // If the opponent doesn't reply gotmove soon enough, re-send move:
1301 // Do this at most 2 times, because mpore would mean network issues,
1302 // opponent would then be expected to disconnect/reconnect.
1304 const currentUrl = document.location.href;
1305 this.retrySendmove = setInterval(
1309 this.opponentGotMove ||
1310 document.location.href != currentUrl //page change
1312 clearInterval(this.retrySendmove);
1315 const oppsid = this.getOppsid();
1317 // Opponent is disconnected: he'll ask last state
1318 clearInterval(this.retrySendmove);
1320 this.send("newmove", { data: sendMove, target: oppsid });
1328 // Not my move or I'm an observer: just start other player's clock
1329 this.re_setClocks();
1332 this.game.type == "corr" &&
1333 moveCol == this.game.mycolor &&
1336 let boardDiv = document.querySelector(".game");
1337 const afterSetScore = () => {
1339 if (this.st.settings.gotonext && this.nextIds.length > 0)
1340 this.showNextGame();
1342 // The board might have been hidden:
1343 if (boardDiv.style.visibility == "hidden")
1344 boardDiv.style.visibility = "visible";
1345 if (data.score == "*") this.re_setClocks();
1348 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1349 // We may play several moves in a row: in case of, remove listener:
1350 let elClone = el.cloneNode(true);
1351 el.parentNode.replaceChild(elClone, el);
1352 elClone.addEventListener(
1355 document.getElementById("modalConfirm").checked = false;
1356 if (!!data.score && data.score != "*")
1358 this.gameOver(data.score, null, afterSetScore);
1359 else afterSetScore();
1362 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1363 V.PlayOnBoard(this.vr.board, move);
1364 const position = this.vr.getBaseFen();
1365 V.UndoOnBoard(this.vr.board, move);
1366 if (["all","byrow"].includes(V.ShowMoves)) {
1367 this.curDiag = getDiagram({
1369 orientation: V.CanFlip ? this.game.mycolor : "w"
1371 document.querySelector("#confirmDiv > .card").style.width =
1372 boardDiv.offsetWidth + "px";
1374 // Incomplete information: just ask confirmation
1375 // Hide the board, because otherwise it could reveal infos
1376 boardDiv.style.visibility = "hidden";
1377 this.moveNotation = getFullNotation(move);
1379 document.getElementById("modalConfirm").checked = true;
1383 if (!!data.score && data.score != "*")
1384 this.gameOver(data.score, null, doProcessMove);
1385 else doProcessMove();
1388 cancelMove: function() {
1389 let boardDiv = document.querySelector(".game");
1390 if (boardDiv.style.visibility == "hidden")
1391 boardDiv.style.visibility = "visible";
1392 document.getElementById("modalConfirm").checked = false;
1393 this.$refs["basegame"].cancelLastMove();
1395 // In corr games, callback to change page only after score is set:
1396 gameOver: function(score, scoreMsg, callback) {
1397 this.game.score = score;
1398 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1399 this.game.scoreMsg = scoreMsg;
1400 this.$set(this.game, "scoreMsg", scoreMsg);
1401 const myIdx = this.game.players.findIndex(p => {
1402 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1405 // OK, I play in this game
1410 if (this.game.type == "live") {
1411 GameStorage.update(this.gameRef, scoreObj);
1412 if (!!callback) callback();
1414 else this.updateCorrGame(scoreObj, callback);
1415 // Notify the score to main Hall. TODO: only one player (currently double send)
1416 this.send("result", { gid: this.game.id, score: score });
1417 // Also to MyGames page (TODO: doubled as well...)
1426 else if (!!callback) callback();
1432 <style lang="sass" scoped>
1438 background-color: lightgreen
1450 @media screen and (min-width: 768px)
1453 @media screen and (max-width: 767px)
1458 display: inline-block
1462 display: inline-block
1464 display: inline-flex
1468 @media screen and (max-width: 767px)
1471 @media screen and (max-width: 767px)
1474 @media screen and (min-width: 768px)
1486 background-color: #edda99
1488 display: inline-block
1497 display: inline-block
1510 animation: blink-animation 2s steps(3, start) infinite
1511 @keyframes blink-animation
1516 display: inline-block
1528 .draw-sent, .draw-sent:hover
1529 background-color: lightyellow
1531 .draw-received, .draw-received:hover
1532 background-color: lightgreen
1534 .draw-threerep, .draw-threerep:hover
1535 background-color: #e4d1fc
1537 .rematch-sent, .rematch-sent:hover
1538 background-color: lightyellow
1540 .rematch-received, .rematch-received:hover
1541 background-color: lightgreen
1544 background-color: #c5fefe
1557 background-color: lightgreen
1559 background-color: red