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 // Callback "roomInit" to poll clients only after game is loaded
633 this.loadVariantThenGame(data.data, this.roomInit);
636 // Sending informative last state if I played a move or score != "*"
637 // If the game or moves aren't loaded yet, delay the sending:
638 // TODO: since socket init after game load, the game is supposedly ready
639 if (!this.game || !this.game.moves) this.lastateAsked = true;
640 else this.sendLastate(data.from);
643 // Got opponent infos about last move
644 this.gotLastate = true;
645 this.lastate = data.data;
646 if (this.game.rendered)
647 // Game is rendered (Board component)
648 this.processLastate();
649 // Else: will be processed when game is ready
653 const movePlus = data.data;
654 const movesCount = this.game.moves.length;
655 if (movePlus.index > movesCount) {
656 // This can only happen if I'm an observer and missed a move.
657 if (this.gotMoveIdx < movePlus.index)
658 this.gotMoveIdx = movePlus.index;
659 if (!this.gameIsLoading) this.askGameAgain();
663 movePlus.index < movesCount ||
664 this.gotMoveIdx >= movePlus.index
666 // Opponent re-send but we already have the move:
667 // (maybe he didn't receive our pingback...)
668 this.send("gotmove", {data: movePlus.index, target: data.from});
670 this.gotMoveIdx = movePlus.index;
671 const receiveMyMove = (movePlus.color == this.game.mycolor);
672 if (!receiveMyMove && !!this.game.mycolor)
673 // Notify opponent that I got the move:
674 this.send("gotmove", {data: movePlus.index, target: data.from});
675 if (movePlus.cancelDrawOffer) {
676 // Opponent refuses draw
678 // NOTE for corr games: drawOffer reset by player in turn
680 this.game.type == "live" &&
681 !!this.game.mycolor &&
684 GameStorage.update(this.gameRef, { drawOffer: "" });
687 this.$refs["basegame"].play(movePlus.move, "received", null, true);
688 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
689 this.game.clocks[moveColIdx] = movePlus.clock;
692 { receiveMyMove: receiveMyMove }
699 this.opponentGotMove = true;
700 // Now his clock starts running on my side:
701 const oppIdx = ['w','b'].indexOf(this.vr.turn);
702 // NOTE: next line to avoid multi-resetClocks when several tabs
703 // on same game, resulting in a faster countdown.
704 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
709 const score = (data.data == "b" ? "1-0" : "0-1");
710 const side = (data.data == "w" ? "White" : "Black");
711 this.gameOver(score, side + " surrender");
714 this.gameOver("?", "Stop");
717 this.gameOver("1/2", data.data);
720 // NOTE: observers don't know who offered draw
721 this.drawOffer = "received";
722 if (this.game.type == "live") {
725 { drawOffer: V.GetOppCol(this.game.mycolor) }
730 // NOTE: observers don't know who offered rematch
731 this.rematchOffer = data.data ? "received" : "";
732 if (this.game.type == "live") {
735 { rematchOffer: V.GetOppCol(this.game.mycolor) }
740 // A game started, redirect if I'm playing in
741 const gameInfo = data.data;
742 const gameType = this.getGameType(gameInfo);
744 gameType == "live" &&
745 gameInfo.players.some(p => p.sid == this.st.user.sid)
747 this.addAndGotoLiveGame(gameInfo);
749 gameType == "corr" &&
750 gameInfo.players.some(p => p.id == this.st.user.id)
752 this.$router.push("/game/" + gameInfo.id);
754 this.rematchId = gameInfo.id;
755 document.getElementById("modalInfo").checked = true;
760 this.$refs["chatcomp"].newChat(data.data);
761 if (!document.getElementById("modalChat").checked)
762 document.getElementById("chatBtn").classList.add("somethingnew");
766 updateCorrGame: function(obj, callback) {
776 if (!!callback) callback();
781 sendLastate: function(target) {
782 // Send our "last state" informations to opponent
783 const L = this.game.moves.length;
784 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
787 (L > 0 && this.vr.turn != this.game.mycolor)
788 ? this.game.moves[L - 1]
790 clock: this.game.clocks[myIdx],
791 // Since we played a move (or abort or resign),
792 // only drawOffer=="sent" is possible
793 drawSent: this.drawOffer == "sent",
794 rematchSent: this.rematchOffer == "sent",
795 score: this.game.score != "*" ? this.game.score : undefined,
796 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
799 this.send("lastate", { data: myLastate, target: target });
801 // lastate was received, but maybe game wasn't ready yet:
802 processLastate: function() {
803 const data = this.lastate;
804 this.lastate = undefined; //security...
805 const L = this.game.moves.length;
806 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
807 this.game.clocks[oppIdx] = data.clock;
808 if (data.movesCount > L) {
809 // Just got last move from him
810 this.$refs["basegame"].play(data.lastMove, "received", null, true);
811 this.processMove(data.lastMove);
813 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
816 if (data.drawSent) this.drawOffer = "received";
817 if (data.rematchSent) this.rematchOffer = "received";
820 if (this.game.score == "*")
821 this.gameOver(data.score, data.scoreMsg);
824 clickDraw: function() {
825 if (!this.game.mycolor) return; //I'm just spectator
826 if (["received", "threerep"].includes(this.drawOffer)) {
827 if (!confirm(this.st.tr["Accept draw?"])) return;
829 this.drawOffer == "received"
831 : "Three repetitions";
832 this.send("draw", { data: message });
833 this.gameOver("1/2", message);
834 } else if (this.drawOffer == "") {
835 // No effect if drawOffer == "sent"
836 if (this.game.mycolor != this.vr.turn) {
837 alert(this.st.tr["Draw offer only in your turn"]);
840 if (!confirm(this.st.tr["Offer draw?"])) return;
841 this.drawOffer = "sent";
842 this.send("drawoffer");
843 if (this.game.type == "live") {
846 { drawOffer: this.game.mycolor }
848 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
851 addAndGotoLiveGame: function(gameInfo, callback) {
852 const game = Object.assign(
856 // (other) Game infos: constant
857 fenStart: gameInfo.fen,
858 vname: this.game.vname,
860 // Game state (including FEN): will be updated
862 clocks: [-1, -1], //-1 = unstarted
866 GameStorage.add(game, (err) => {
867 // No error expected.
869 if (this.st.settings.sound)
870 new Audio("/sounds/newgame.flac").play().catch(() => {});
871 if (!!callback) callback();
872 this.$router.push("/game/" + gameInfo.id);
876 clickRematch: function() {
877 if (!this.game.mycolor) return; //I'm just spectator
878 if (this.rematchOffer == "received") {
881 id: getRandString(), //ignored if corr
882 fen: V.GenRandInitFen(this.game.randomness),
883 players: this.game.players.reverse(),
885 cadence: this.game.cadence
887 const notifyNewGame = () => {
888 const oppsid = this.getOppsid(); //may be null
889 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
890 // To main Hall if corr game:
891 if (this.game.type == "corr")
892 this.send("newgame", { data: gameInfo, page: "/" });
893 // Also to MyGames page:
894 this.notifyMyGames("newgame", gameInfo);
896 if (this.game.type == "live")
897 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
904 // cid is useful to delete the challenge:
905 data: { gameInfo: gameInfo },
906 success: (response) => {
907 gameInfo.id = response.gameId;
909 this.$router.push("/game/" + response.gameId);
914 } else if (this.rematchOffer == "") {
915 this.rematchOffer = "sent";
916 this.send("rematchoffer", { data: true });
917 if (this.game.type == "live") {
920 { rematchOffer: this.game.mycolor }
922 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
923 } else if (this.rematchOffer == "sent") {
924 // Toggle rematch offer (on --> off)
925 this.rematchOffer = "";
926 this.send("rematchoffer", { data: false });
927 if (this.game.type == "live") {
932 } else this.updateCorrGame({ rematchOffer: 'n' });
935 abortGame: function() {
936 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
937 this.gameOver("?", "Stop");
941 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
943 this.send("resign", { data: this.game.mycolor });
944 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
945 const side = (this.game.mycolor == "w" ? "White" : "Black");
946 this.gameOver(score, side + " surrender");
948 loadGame: function(game, callback) {
949 this.vr = new V(game.fen);
950 const gtype = this.getGameType(game);
951 const tc = extractTime(game.cadence);
952 const myIdx = game.players.findIndex(p => {
953 return p.sid == this.st.user.sid || p.id == this.st.user.id;
955 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
956 if (!game.chats) game.chats = []; //live games don't have chat history
957 if (gtype == "corr") {
958 // NOTE: clocks in seconds
959 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
960 game.clocks = [tc.mainTime, tc.mainTime];
961 const L = game.moves.length;
962 if (game.score == "*") {
965 game.clocks[L % 2] -=
966 (Date.now() - game.moves[L-1].played) / 1000;
969 // Sort chat messages from newest to oldest
970 game.chats.sort((c1, c2) => {
971 return c2.added - c1.added;
973 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
974 // Did a chat message arrive after my last move?
976 if (L == 1 && myIdx == 0)
977 dtLastMove = game.moves[0].played;
980 // It's now white turn
981 dtLastMove = game.moves[L-1-(1-myIdx)].played;
984 dtLastMove = game.moves[L-1-myIdx].played;
987 if (dtLastMove < game.chats[0].added)
988 document.getElementById("chatBtn").classList.add("somethingnew");
990 // Now that we used idx and played, re-format moves as for live games
991 game.moves = game.moves.map(m => m.squares);
993 if (gtype == "live") {
994 if (game.clocks[0] < 0) {
995 // Game is unstarted. clock is ignored until move 2
996 game.clocks = [tc.mainTime, tc.mainTime];
998 // I play in this live game
999 GameStorage.update(game.id, {
1005 // It's my turn: clocks not updated yet
1006 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1009 // TODO: merge next 2 "if" conditions
1010 if (!!game.drawOffer) {
1011 if (game.drawOffer == "t")
1012 // Three repetitions
1013 this.drawOffer = "threerep";
1015 // Draw offered by any of the players:
1016 if (myIdx < 0) this.drawOffer = "received";
1018 // I play in this game:
1020 (game.drawOffer == "w" && myIdx == 0) ||
1021 (game.drawOffer == "b" && myIdx == 1)
1023 this.drawOffer = "sent";
1024 else this.drawOffer = "received";
1028 if (!!game.rematchOffer) {
1029 if (myIdx < 0) this.rematchOffer = "received";
1031 // I play in this game:
1033 (game.rematchOffer == "w" && myIdx == 0) ||
1034 (game.rematchOffer == "b" && myIdx == 1)
1036 this.rematchOffer = "sent";
1037 else this.rematchOffer = "received";
1040 this.repeat = {}; //reset: scan past moves' FEN:
1042 let vr_tmp = new V(game.fenStart);
1044 game.moves.forEach(m => {
1045 playMove(m, vr_tmp);
1046 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1047 this.repeat[fenIdx] = this.repeat[fenIdx]
1048 ? this.repeat[fenIdx] + 1
1051 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1052 this.game = Object.assign(
1053 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1056 increment: tc.increment,
1058 // opponent sid not strictly required (or available), but easier
1059 // at least oppsid or oppid is available anyway:
1060 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1061 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1065 this.$refs["basegame"].re_setVariables(this.game);
1066 if (!this.gameIsLoading) {
1068 this.gotMoveIdx = game.moves.length - 1;
1069 // If we arrive here after 'nextGame' action, the board might be hidden
1070 let boardDiv = document.querySelector(".game");
1071 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1072 boardDiv.style.visibility = "visible";
1074 this.re_setClocks();
1075 this.$nextTick(() => {
1076 this.game.rendered = true;
1077 // Did lastate arrive before game was rendered?
1078 if (this.lastate) this.processLastate();
1080 if (this.lastateAsked) {
1081 this.lastateAsked = false;
1082 this.sendLastate(game.oppsid);
1084 if (this.gameIsLoading) {
1085 this.gameIsLoading = false;
1086 if (this.gotMoveIdx >= game.moves.length)
1087 // Some moves arrived meanwhile...
1088 this.askGameAgain();
1090 if (!!callback) callback();
1092 loadVariantThenGame: async function(game, callback) {
1093 await import("@/variants/" + game.vname + ".js")
1094 .then((vModule) => {
1095 window.V = vModule[game.vname + "Rules"];
1096 this.loadGame(game, callback);
1099 // 3 cases for loading a game:
1100 // - from indexedDB (running or completed live game I play)
1101 // - from server (one correspondance game I play[ed] or not)
1102 // - from remote peer (one live game I don't play, finished or not)
1103 fetchGame: function(callback) {
1104 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1105 // corr games identifiers are integers
1110 data: { gid: this.gameRef },
1112 res.game.moves.forEach(m => {
1113 m.squares = JSON.parse(m.squares);
1120 // Local game (or live remote)
1121 GameStorage.get(this.gameRef, callback);
1123 re_setClocks: function() {
1124 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1125 if (this.game.moves.length < 2 || this.game.score != "*") {
1126 // 1st move not completed yet, or game over: freeze time
1129 const currentTurn = this.vr.turn;
1130 const currentMovesCount = this.game.moves.length;
1131 const colorIdx = ["w", "b"].indexOf(currentTurn);
1132 this.clockUpdate = setInterval(
1135 this.game.clocks[colorIdx] < 0 ||
1136 this.game.moves.length > currentMovesCount ||
1137 this.game.score != "*"
1139 clearInterval(this.clockUpdate);
1140 this.clockUpdate = null;
1141 if (this.game.clocks[colorIdx] < 0)
1143 currentTurn == "w" ? "0-1" : "1-0",
1150 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1157 // Update variables and storage after a move:
1158 processMove: function(move, data) {
1159 if (!data) data = {};
1160 const moveCol = this.vr.turn;
1161 const colorIdx = ["w", "b"].indexOf(moveCol);
1162 const nextIdx = 1 - colorIdx;
1163 const doProcessMove = () => {
1164 const origMovescount = this.game.moves.length;
1165 // The move is (about to be) played: stop clock
1166 clearInterval(this.clockUpdate);
1167 this.clockUpdate = null;
1168 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1169 if (this.drawOffer == "received")
1171 this.drawOffer = "";
1172 if (this.game.type == "live" && origMovescount >= 2) {
1173 this.game.clocks[colorIdx] += this.game.increment;
1174 // For a correct display in casqe of disconnected opponent:
1178 ppt(this.game.clocks[colorIdx]).split(':')
1180 GameStorage.update(this.gameRef, {
1181 // It's not my turn anymore:
1186 // Update current game object:
1187 playMove(move, this.vr);
1189 // Received move, score is computed in BaseGame, but maybe not yet.
1190 // ==> Compute it here, although this is redundant (TODO)
1191 data.score = this.vr.getCurrentScore();
1192 if (data.score != "*") this.gameOver(data.score);
1193 this.game.moves.push(move);
1194 this.game.fen = this.vr.getFen();
1195 if (this.game.type == "corr") {
1196 // In corr games, just reset clock to mainTime:
1197 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1199 // If repetition detected, consider that a draw offer was received:
1200 const fenObj = this.vr.getFenForRepeat();
1201 this.repeat[fenObj] =
1202 !!this.repeat[fenObj]
1203 ? this.repeat[fenObj] + 1
1205 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1206 else if (this.drawOffer == "threerep") this.drawOffer = "";
1207 if (!!this.game.mycolor && !data.receiveMyMove) {
1208 // NOTE: 'var' to see that variable outside this block
1209 var filtered_move = getFilteredMove(move);
1211 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1212 // Notify turn on MyGames page:
1221 // Since corr games are stored at only one location, update should be
1222 // done only by one player for each move:
1224 this.game.type == "live" &&
1225 !!this.game.mycolor &&
1226 moveCol != this.game.mycolor &&
1227 this.game.moves.length >= 2
1229 // Receive a move: update initime
1230 this.game.initime = Date.now();
1231 GameStorage.update(this.gameRef, {
1232 // It's my turn now!
1233 initime: this.game.initime
1237 !!this.game.mycolor &&
1238 !data.receiveMyMove &&
1239 (this.game.type == "live" || moveCol == this.game.mycolor)
1242 switch (this.drawOffer) {
1247 drawCode = this.game.mycolor;
1250 drawCode = V.GetOppCol(this.game.mycolor);
1253 if (this.game.type == "corr") {
1254 // corr: only move, fen and score
1255 this.updateCorrGame({
1258 squares: filtered_move,
1261 // Code "n" for "None" to force reset (otherwise it's ignored)
1262 drawOffer: drawCode || "n"
1266 const updateStorage = () => {
1267 GameStorage.update(this.gameRef, {
1269 move: filtered_move,
1270 moveIdx: origMovescount,
1271 clocks: this.game.clocks,
1275 // The active tab can update storage immediately
1276 if (!document.hidden) updateStorage();
1277 // Small random delay otherwise
1278 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1281 // Send move ("newmove" event) to people in the room (if our turn)
1282 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1284 move: filtered_move,
1285 index: origMovescount,
1286 // color is required to check if this is my move (if several tabs opened)
1288 cancelDrawOffer: this.drawOffer == ""
1290 if (this.game.type == "live")
1291 sendMove["clock"] = this.game.clocks[colorIdx];
1292 // (Live) Clocks will re-start when the opponent pingback arrive
1293 this.opponentGotMove = false;
1294 this.send("newmove", {data: sendMove});
1295 // If the opponent doesn't reply gotmove soon enough, re-send move:
1296 // Do this at most 2 times, because mpore would mean network issues,
1297 // opponent would then be expected to disconnect/reconnect.
1299 const currentUrl = document.location.href;
1300 this.retrySendmove = setInterval(
1304 this.opponentGotMove ||
1305 document.location.href != currentUrl //page change
1307 clearInterval(this.retrySendmove);
1310 const oppsid = this.getOppsid();
1312 // Opponent is disconnected: he'll ask last state
1313 clearInterval(this.retrySendmove);
1315 this.send("newmove", { data: sendMove, target: oppsid });
1323 // Not my move or I'm an observer: just start other player's clock
1324 this.re_setClocks();
1327 this.game.type == "corr" &&
1328 moveCol == this.game.mycolor &&
1331 let boardDiv = document.querySelector(".game");
1332 const afterSetScore = () => {
1334 if (this.st.settings.gotonext && this.nextIds.length > 0)
1335 this.showNextGame();
1337 // The board might have been hidden:
1338 if (boardDiv.style.visibility == "hidden")
1339 boardDiv.style.visibility = "visible";
1340 if (data.score == "*") this.re_setClocks();
1343 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1344 // We may play several moves in a row: in case of, remove listener:
1345 let elClone = el.cloneNode(true);
1346 el.parentNode.replaceChild(elClone, el);
1347 elClone.addEventListener(
1350 document.getElementById("modalConfirm").checked = false;
1351 if (!!data.score && data.score != "*")
1353 this.gameOver(data.score, null, afterSetScore);
1354 else afterSetScore();
1357 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1358 V.PlayOnBoard(this.vr.board, move);
1359 const position = this.vr.getBaseFen();
1360 V.UndoOnBoard(this.vr.board, move);
1361 if (["all","byrow"].includes(V.ShowMoves)) {
1362 this.curDiag = getDiagram({
1364 orientation: V.CanFlip ? this.game.mycolor : "w"
1366 document.querySelector("#confirmDiv > .card").style.width =
1367 boardDiv.offsetWidth + "px";
1369 // Incomplete information: just ask confirmation
1370 // Hide the board, because otherwise it could reveal infos
1371 boardDiv.style.visibility = "hidden";
1372 this.moveNotation = getFullNotation(move);
1374 document.getElementById("modalConfirm").checked = true;
1378 if (!!data.score && data.score != "*")
1379 this.gameOver(data.score, null, doProcessMove);
1380 else doProcessMove();
1383 cancelMove: function() {
1384 let boardDiv = document.querySelector(".game");
1385 if (boardDiv.style.visibility == "hidden")
1386 boardDiv.style.visibility = "visible";
1387 document.getElementById("modalConfirm").checked = false;
1388 this.$refs["basegame"].cancelLastMove();
1390 // In corr games, callback to change page only after score is set:
1391 gameOver: function(score, scoreMsg, callback) {
1392 this.game.score = score;
1393 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1394 this.game.scoreMsg = scoreMsg;
1395 this.$set(this.game, "scoreMsg", scoreMsg);
1396 const myIdx = this.game.players.findIndex(p => {
1397 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1400 // OK, I play in this game
1405 if (this.game.type == "live") {
1406 GameStorage.update(this.gameRef, scoreObj);
1407 if (!!callback) callback();
1409 else this.updateCorrGame(scoreObj, callback);
1410 // Notify the score to main Hall. TODO: only one player (currently double send)
1411 this.send("result", { gid: this.game.id, score: score });
1412 // Also to MyGames page (TODO: doubled as well...)
1421 else if (!!callback) callback();
1427 <style lang="sass" scoped>
1433 background-color: lightgreen
1445 @media screen and (min-width: 768px)
1448 @media screen and (max-width: 767px)
1453 display: inline-block
1457 display: inline-block
1459 display: inline-flex
1463 @media screen and (max-width: 767px)
1466 @media screen and (max-width: 767px)
1469 @media screen and (min-width: 768px)
1481 background-color: #edda99
1483 display: inline-block
1492 display: inline-block
1505 animation: blink-animation 2s steps(3, start) infinite
1506 @keyframes blink-animation
1511 display: inline-block
1523 .draw-sent, .draw-sent:hover
1524 background-color: lightyellow
1526 .draw-received, .draw-received:hover
1527 background-color: lightgreen
1529 .draw-threerep, .draw-threerep:hover
1530 background-color: #e4d1fc
1532 .rematch-sent, .rematch-sent:hover
1533 background-color: lightyellow
1535 .rematch-received, .rematch-received:hover
1536 background-color: lightgreen
1539 background-color: #c5fefe
1552 background-color: lightgreen
1554 background-color: red