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 // Incomplete info games: show move played
181 // Intervals from setInterval():
185 // Related to (killing of) self multi-connects:
191 $route: function(to, from) {
192 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
194 this.cleanBeforeDestroy();
195 else if (from.params["id"] != to.params["id"]) {
196 // Change everything:
197 this.cleanBeforeDestroy();
198 let boardDiv = document.querySelector(".game");
200 // In case of incomplete information variant:
201 boardDiv.style.visibility = "hidden";
205 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
208 // NOTE: some redundant code with Hall.vue (mostly related to people array)
209 created: function() {
212 mounted: function() {
213 ["chatWrap", "infoDiv"].forEach(eltName => {
214 document.getElementById(eltName)
215 .addEventListener("click", processModalClick);
217 if ("ontouchstart" in window) {
218 // Disable tooltips on smartphones:
219 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
220 elt.classList.remove("tooltip");
224 beforeDestroy: function() {
225 this.cleanBeforeDestroy();
228 cleanBeforeDestroy: function() {
229 document.removeEventListener('visibilitychange', this.visibilityChange);
230 if (!!this.askLastate) clearInterval(this.askLastate);
231 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
232 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
233 this.conn.removeEventListener("message", this.socketMessageListener);
234 this.conn.removeEventListener("close", this.socketCloseListener);
235 this.send("disconnect");
238 visibilityChange: function() {
239 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
241 document.visibilityState == "visible"
246 participateInChat: function(p) {
247 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
249 someAnonymousPresent: function() {
251 Object.values(this.people).some(p =>
252 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
256 atCreation: function() {
257 document.addEventListener('visibilitychange', this.visibilityChange);
258 // 0] (Re)Set variables
259 this.gameRef = this.$route.params["id"];
260 // next = next corr games IDs to navigate faster (if applicable)
261 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
262 // Always add myself to players' list
263 const my = this.st.user;
264 const tmpId = getRandString();
272 tmpId: { focus: true }
277 players: [{ name: "" }, { name: "" }],
281 let chatComp = this.$refs["chatcomp"];
282 if (!!chatComp) chatComp.chats = [];
283 this.virtualClocks = [[0,0], [0,0]];
286 this.lastateAsked = false;
287 this.rematchOffer = "";
288 this.lastate = undefined;
289 this.roomInitialized = false;
290 this.askGameTime = 0;
291 this.gameIsLoading = false;
292 this.gotLastate = false;
293 this.gotMoveIdx = -1;
294 this.opponentGotMove = false;
295 this.askLastate = null;
296 this.retrySendmove = null;
297 this.clockUpdate = null;
298 this.newConnect = {};
300 // 1] Initialize connection
301 this.connexionString =
303 "/?sid=" + this.st.user.sid +
304 "&id=" + this.st.user.id +
307 // Discard potential "/?next=[...]" for page indication:
308 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
309 this.conn = new WebSocket(this.connexionString);
310 this.conn.addEventListener("message", this.socketMessageListener);
311 this.conn.addEventListener("close", this.socketCloseListener);
312 // Socket init required before loading remote game:
313 const socketInit = callback => {
314 if (this.conn.readyState == 1)
318 // Socket not ready yet (initial loading)
319 // NOTE: first arg is Websocket object, unused here:
320 this.conn.onopen = () => callback();
322 this.fetchGame((game) => {
324 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
326 // Live game stored remotely: need socket to retrieve it
327 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
328 // --> It will be given when receiving "fullgame" socket event.
329 socketInit(() => { this.send("askfullgame"); });
332 roomInit: function() {
333 if (!this.roomInitialized) {
334 // Notify the room only now that I connected, because
335 // messages might be lost otherwise (if game loading is slow)
336 this.send("connect");
337 this.send("pollclients");
338 // We may ask fullgame several times if some moves are lost,
339 // but room should be init only once:
340 this.roomInitialized = true;
343 send: function(code, obj) {
345 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
347 isConnected: function(index) {
348 const player = this.game.players[index];
349 // Is it me ? In this case no need to bother with focus
350 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
351 // Still have to check for name (because of potential multi-accounts
352 // on same browser, although this should be rare...)
353 return (!this.st.user.name || this.st.user.name == player.name);
354 // Try to find a match in people:
358 Object.keys(this.people).some(sid => {
361 Object.values(this.people[sid].tmpIds).some(v => v.focus)
368 Object.values(this.people).some(p => {
371 Object.values(p.tmpIds).some(v => v.focus)
377 getOppsid: function() {
378 let oppsid = this.game.oppsid;
380 oppsid = Object.keys(this.people).find(
381 sid => this.people[sid].id == this.game.oppid
384 // oppsid is useful only if opponent is online:
385 if (!!oppsid && !!this.people[oppsid]) return oppsid;
388 toggleChat: function() {
389 if (document.getElementById("modalChat").checked)
391 document.getElementById("inputChat").focus();
392 // TODO: next line is only required when exiting chat,
393 // but the event for now isn't well detected.
394 document.getElementById("chatBtn").classList.remove("somethingnew");
396 processChat: function(chat) {
397 this.send("newchat", { data: chat });
398 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
399 if (this.game.type == "corr" && this.st.user.id > 0)
400 this.updateCorrGame({ chat: chat });
402 clearChat: function() {
403 // Nothing more to do if game is live (chats not recorded)
404 if (this.game.type == "corr") {
405 if (!!this.game.mycolor) {
409 { data: { gid: this.game.id } }
412 this.$set(this.game, "chats", []);
415 getGameType: function(game) {
416 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
418 // Notify something after a new move (to opponent and me on MyGames page)
419 notifyMyGames: function(thing, data) {
424 targets: this.game.players.map(p => {
425 return { sid: p.sid, id: p.id };
430 showNextGame: function() {
431 // Did I play in current game? If not, add it to nextIds list
432 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
433 this.nextIds.unshift(this.game.id);
434 const nextGid = this.nextIds.pop();
436 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
438 askGameAgain: function() {
439 this.gameIsLoading = true;
440 const currentUrl = document.location.href;
441 const doAskGame = () => {
442 if (document.location.href != currentUrl) return; //page change
443 this.fetchGame((game) => {
445 // This is my game: just reload.
448 // Just ask fullgame again (once!), this is much simpler.
449 // If this fails, the user could just reload page :/
450 this.send("askfullgame");
453 // Delay of at least 2s between two game requests
454 const now = Date.now();
455 const delay = Math.max(2000 - (now - this.askGameTime), 0);
456 this.askGameTime = now;
457 setTimeout(doAskGame, delay);
459 socketMessageListener: function(msg) {
460 if (!this.conn) return;
461 const data = JSON.parse(msg.data);
464 // TODO: shuffling and random filtering on server,
465 // if the room is really crowded.
466 Object.keys(data.sockIds).forEach(sid => {
467 // TODO: test sid != user.sid was already done on server
468 if (sid != this.st.user.sid) {
469 this.people[sid] = { tmpIds: data.sockIds[sid] };
470 this.send("askidentity", { target: sid });
475 if (!this.people[data.from[0]]) {
476 // focus depends on the tmpId (e.g. tab)
482 [data.from[1]]: { focus: true }
486 this.newConnect[data.from] = true; //for self multi-connects tests
487 this.send("askidentity", { target: data.from[0] });
489 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
490 this.$forceUpdate(); //TODO: shouldn't be required
494 if (!this.people[data.from[0]]) return;
495 delete this.people[data.from[0]].tmpIds[data.from[1]];
496 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
497 this.$delete(this.people, data.from[0]);
498 else this.$forceUpdate(); //TODO: shouldn't be required
501 let player = this.people[data.from[0]];
503 player.tmpIds[data.from[1]].focus = true;
504 this.$forceUpdate(); //TODO: shouldn't be required
509 let player = this.people[data.from[0]];
511 player.tmpIds[data.from[1]].focus = false;
512 this.$forceUpdate(); //TODO: shouldn't be required
517 // I logged in elsewhere:
518 this.conn.removeEventListener("message", this.socketMessageListener);
519 this.conn.removeEventListener("close", this.socketCloseListener);
521 alert(this.st.tr["New connexion detected: tab now offline"]);
523 case "askidentity": {
524 // Request for identification
526 // Decompose to avoid revealing email
527 name: this.st.user.name,
528 sid: this.st.user.sid,
531 this.send("identity", { data: me, target: data.from });
535 const user = data.data;
536 let player = this.people[user.sid];
537 // player.tmpIds is already set
538 player.name = user.name;
540 this.$forceUpdate(); //TODO: shouldn't be required
541 // If I multi-connect, kill current connexion if no mark (I'm older)
542 if (this.newConnect[user.sid]) {
545 user.id == this.st.user.id &&
546 user.sid != this.st.user.sid &&
547 !this.killed[this.st.user.sid]
549 this.send("killme", { sid: this.st.user.sid });
550 this.killed[this.st.user.sid] = true;
552 delete this.newConnect[user.sid];
554 if (!this.killed[this.st.user.sid]) {
555 // Ask potentially missed last state, if opponent and I play
558 !!this.game.mycolor &&
559 this.game.type == "live" &&
560 this.game.score == "*" &&
561 this.game.players.some(p => p.sid == user.sid)
563 this.send("asklastate", { target: user.sid });
565 this.askLastate = setInterval(
567 // Ask at most 3 times:
568 // if no reply after that there should be a network issue.
572 !!this.people[user.sid]
574 this.send("asklastate", { target: user.sid });
577 clearInterval(this.askLastate);
587 // Send current (live) game if not asked by any of the players
589 this.game.type == "live" &&
590 this.game.players.every(p => p.sid != data.from[0])
595 players: this.game.players,
597 cadence: this.game.cadence,
598 score: this.game.score
600 this.send("game", { data: myGame, target: data.from });
604 const gameToSend = Object.keys(this.game)
607 "id","fen","players","vid","cadence","fenStart","vname",
608 "moves","clocks","score","drawOffer","rematchOffer"
612 obj[k] = this.game[k];
617 this.send("fullgame", { data: gameToSend, target: data.from });
620 // Callback "roomInit" to poll clients only after game is loaded
621 this.loadVariantThenGame(data.data, this.roomInit);
624 // Sending informative last state if I played a move or score != "*"
625 // If the game or moves aren't loaded yet, delay the sending:
626 // TODO: since socket init after game load, the game is supposedly ready
627 if (!this.game || !this.game.moves) this.lastateAsked = true;
628 else this.sendLastate(data.from);
631 // Got opponent infos about last move
632 this.gotLastate = true;
633 this.lastate = data.data;
634 if (this.game.rendered)
635 // Game is rendered (Board component)
636 this.processLastate();
637 // Else: will be processed when game is ready
641 const movePlus = data.data;
642 const movesCount = this.game.moves.length;
643 if (movePlus.index > movesCount) {
644 // This can only happen if I'm an observer and missed a move.
645 if (this.gotMoveIdx < movePlus.index)
646 this.gotMoveIdx = movePlus.index;
647 if (!this.gameIsLoading) this.askGameAgain();
651 movePlus.index < movesCount ||
652 this.gotMoveIdx >= movePlus.index
654 // Opponent re-send but we already have the move:
655 // (maybe he didn't receive our pingback...)
656 this.send("gotmove", {data: movePlus.index, target: data.from});
658 this.gotMoveIdx = movePlus.index;
659 const receiveMyMove = (movePlus.color == this.game.mycolor);
660 if (!receiveMyMove && !!this.game.mycolor)
661 // Notify opponent that I got the move:
662 this.send("gotmove", {data: movePlus.index, target: data.from});
663 if (movePlus.cancelDrawOffer) {
664 // Opponent refuses draw
666 // NOTE for corr games: drawOffer reset by player in turn
668 this.game.type == "live" &&
669 !!this.game.mycolor &&
672 GameStorage.update(this.gameRef, { drawOffer: "" });
675 this.$refs["basegame"].play(movePlus.move, "received", null, true);
676 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
677 this.game.clocks[moveColIdx] = movePlus.clock;
680 { receiveMyMove: receiveMyMove }
687 this.opponentGotMove = true;
688 // Now his clock starts running on my side:
689 const oppIdx = ['w','b'].indexOf(this.vr.turn);
690 // NOTE: next line to avoid multi-resetClocks when several tabs
691 // on same game, resulting in a faster countdown.
692 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
697 const score = (data.data == "b" ? "1-0" : "0-1");
698 const side = (data.data == "w" ? "White" : "Black");
699 this.gameOver(score, side + " surrender");
702 this.gameOver("?", "Stop");
705 this.gameOver("1/2", data.data);
708 // NOTE: observers don't know who offered draw
709 this.drawOffer = "received";
710 if (this.game.type == "live") {
713 { drawOffer: V.GetOppCol(this.game.mycolor) }
718 // NOTE: observers don't know who offered rematch
719 this.rematchOffer = data.data ? "received" : "";
720 if (this.game.type == "live") {
723 { rematchOffer: V.GetOppCol(this.game.mycolor) }
728 // A game started, redirect if I'm playing in
729 const gameInfo = data.data;
730 const gameType = this.getGameType(gameInfo);
732 gameType == "live" &&
733 gameInfo.players.some(p => p.sid == this.st.user.sid)
735 this.addAndGotoLiveGame(gameInfo);
737 gameType == "corr" &&
738 gameInfo.players.some(p => p.id == this.st.user.id)
740 this.$router.push("/game/" + gameInfo.id);
742 this.rematchId = gameInfo.id;
743 document.getElementById("modalInfo").checked = true;
748 this.$refs["chatcomp"].newChat(data.data);
749 if (!document.getElementById("modalChat").checked)
750 document.getElementById("chatBtn").classList.add("somethingnew");
754 socketCloseListener: function() {
755 this.conn = new WebSocket(this.connexionString);
756 this.conn.addEventListener("message", this.socketMessageListener);
757 this.conn.addEventListener("close", this.socketCloseListener);
759 updateCorrGame: function(obj, callback) {
769 if (!!callback) callback();
774 sendLastate: function(target) {
775 // Send our "last state" informations to opponent
776 const L = this.game.moves.length;
777 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
780 (L > 0 && this.vr.turn != this.game.mycolor)
781 ? this.game.moves[L - 1]
783 clock: this.game.clocks[myIdx],
784 // Since we played a move (or abort or resign),
785 // only drawOffer=="sent" is possible
786 drawSent: this.drawOffer == "sent",
787 rematchSent: this.rematchOffer == "sent",
788 score: this.game.score != "*" ? this.game.score : undefined,
789 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
792 this.send("lastate", { data: myLastate, target: target });
794 // lastate was received, but maybe game wasn't ready yet:
795 processLastate: function() {
796 const data = this.lastate;
797 this.lastate = undefined; //security...
798 const L = this.game.moves.length;
799 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
800 this.game.clocks[oppIdx] = data.clock;
801 if (data.movesCount > L) {
802 // Just got last move from him
803 this.$refs["basegame"].play(data.lastMove, "received", null, true);
804 this.processMove(data.lastMove);
806 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
809 if (data.drawSent) this.drawOffer = "received";
810 if (data.rematchSent) this.rematchOffer = "received";
813 if (this.game.score == "*")
814 this.gameOver(data.score, data.scoreMsg);
817 clickDraw: function() {
818 if (!this.game.mycolor) return; //I'm just spectator
819 if (["received", "threerep"].includes(this.drawOffer)) {
820 if (!confirm(this.st.tr["Accept draw?"])) return;
822 this.drawOffer == "received"
824 : "Three repetitions";
825 this.send("draw", { data: message });
826 this.gameOver("1/2", message);
827 } else if (this.drawOffer == "") {
828 // No effect if drawOffer == "sent"
829 if (this.game.mycolor != this.vr.turn) {
830 alert(this.st.tr["Draw offer only in your turn"]);
833 if (!confirm(this.st.tr["Offer draw?"])) return;
834 this.drawOffer = "sent";
835 this.send("drawoffer");
836 if (this.game.type == "live") {
839 { drawOffer: this.game.mycolor }
841 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
844 addAndGotoLiveGame: function(gameInfo, callback) {
845 const game = Object.assign(
849 // (other) Game infos: constant
850 fenStart: gameInfo.fen,
851 vname: this.game.vname,
853 // Game state (including FEN): will be updated
855 clocks: [-1, -1], //-1 = unstarted
859 GameStorage.add(game, (err) => {
860 // No error expected.
862 if (this.st.settings.sound)
863 new Audio("/sounds/newgame.flac").play().catch(() => {});
864 if (!!callback) callback();
865 this.$router.push("/game/" + gameInfo.id);
869 clickRematch: function() {
870 if (!this.game.mycolor) return; //I'm just spectator
871 if (this.rematchOffer == "received") {
874 id: getRandString(), //ignored if corr
875 fen: V.GenRandInitFen(this.game.randomness),
876 players: this.game.players.reverse(),
878 cadence: this.game.cadence
880 const notifyNewGame = () => {
881 const oppsid = this.getOppsid(); //may be null
882 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
883 // To main Hall if corr game:
884 if (this.game.type == "corr")
885 this.send("newgame", { data: gameInfo, page: "/" });
886 // Also to MyGames page:
887 this.notifyMyGames("newgame", gameInfo);
889 if (this.game.type == "live")
890 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
897 // cid is useful to delete the challenge:
898 data: { gameInfo: gameInfo },
899 success: (response) => {
900 gameInfo.id = response.gameId;
902 this.$router.push("/game/" + response.gameId);
907 } else if (this.rematchOffer == "") {
908 this.rematchOffer = "sent";
909 this.send("rematchoffer", { data: true });
910 if (this.game.type == "live") {
913 { rematchOffer: this.game.mycolor }
915 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
916 } else if (this.rematchOffer == "sent") {
917 // Toggle rematch offer (on --> off)
918 this.rematchOffer = "";
919 this.send("rematchoffer", { data: false });
920 if (this.game.type == "live") {
925 } else this.updateCorrGame({ rematchOffer: 'n' });
928 abortGame: function() {
929 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
930 this.gameOver("?", "Stop");
934 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
936 this.send("resign", { data: this.game.mycolor });
937 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
938 const side = (this.game.mycolor == "w" ? "White" : "Black");
939 this.gameOver(score, side + " surrender");
941 loadGame: function(game, callback) {
942 this.vr = new V(game.fen);
943 const gtype = this.getGameType(game);
944 const tc = extractTime(game.cadence);
945 const myIdx = game.players.findIndex(p => {
946 return p.sid == this.st.user.sid || p.id == this.st.user.id;
948 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
949 if (!game.chats) game.chats = []; //live games don't have chat history
950 if (gtype == "corr") {
951 // NOTE: clocks in seconds
952 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
953 game.clocks = [tc.mainTime, tc.mainTime];
954 const L = game.moves.length;
955 if (game.score == "*") {
958 game.clocks[L % 2] -=
959 (Date.now() - game.moves[L-1].played) / 1000;
962 // Sort chat messages from newest to oldest
963 game.chats.sort((c1, c2) => {
964 return c2.added - c1.added;
966 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
967 // Did a chat message arrive after my last move?
969 if (L == 1 && myIdx == 0)
970 dtLastMove = game.moves[0].played;
973 // It's now white turn
974 dtLastMove = game.moves[L-1-(1-myIdx)].played;
977 dtLastMove = game.moves[L-1-myIdx].played;
980 if (dtLastMove < game.chats[0].added)
981 document.getElementById("chatBtn").classList.add("somethingnew");
983 // Now that we used idx and played, re-format moves as for live games
984 game.moves = game.moves.map(m => m.squares);
986 if (gtype == "live") {
987 if (game.clocks[0] < 0) {
988 // Game is unstarted. clock is ignored until move 2
989 game.clocks = [tc.mainTime, tc.mainTime];
991 // I play in this live game
992 GameStorage.update(game.id, {
998 // It's my turn: clocks not updated yet
999 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1002 // TODO: merge next 2 "if" conditions
1003 if (!!game.drawOffer) {
1004 if (game.drawOffer == "t")
1005 // Three repetitions
1006 this.drawOffer = "threerep";
1008 // Draw offered by any of the players:
1009 if (myIdx < 0) this.drawOffer = "received";
1011 // I play in this game:
1013 (game.drawOffer == "w" && myIdx == 0) ||
1014 (game.drawOffer == "b" && myIdx == 1)
1016 this.drawOffer = "sent";
1017 else this.drawOffer = "received";
1021 if (!!game.rematchOffer) {
1022 if (myIdx < 0) this.rematchOffer = "received";
1024 // I play in this game:
1026 (game.rematchOffer == "w" && myIdx == 0) ||
1027 (game.rematchOffer == "b" && myIdx == 1)
1029 this.rematchOffer = "sent";
1030 else this.rematchOffer = "received";
1033 this.repeat = {}; //reset: scan past moves' FEN:
1035 let vr_tmp = new V(game.fenStart);
1037 game.moves.forEach(m => {
1038 playMove(m, vr_tmp);
1039 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1040 this.repeat[fenIdx] = this.repeat[fenIdx]
1041 ? this.repeat[fenIdx] + 1
1044 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1045 this.game = Object.assign(
1046 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1049 increment: tc.increment,
1051 // opponent sid not strictly required (or available), but easier
1052 // at least oppsid or oppid is available anyway:
1053 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1054 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1058 this.$refs["basegame"].re_setVariables(this.game);
1059 if (!this.gameIsLoading) {
1061 this.gotMoveIdx = game.moves.length - 1;
1062 // If we arrive here after 'nextGame' action, the board might be hidden
1063 let boardDiv = document.querySelector(".game");
1064 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1065 boardDiv.style.visibility = "visible";
1067 this.re_setClocks();
1068 this.$nextTick(() => {
1069 this.game.rendered = true;
1070 // Did lastate arrive before game was rendered?
1071 if (this.lastate) this.processLastate();
1073 if (this.lastateAsked) {
1074 this.lastateAsked = false;
1075 this.sendLastate(game.oppsid);
1077 if (this.gameIsLoading) {
1078 this.gameIsLoading = false;
1079 if (this.gotMoveIdx >= game.moves.length)
1080 // Some moves arrived meanwhile...
1081 this.askGameAgain();
1083 if (!!callback) callback();
1085 loadVariantThenGame: async function(game, callback) {
1086 await import("@/variants/" + game.vname + ".js")
1087 .then((vModule) => {
1088 window.V = vModule[game.vname + "Rules"];
1089 this.loadGame(game, callback);
1092 // 3 cases for loading a game:
1093 // - from indexedDB (running or completed live game I play)
1094 // - from server (one correspondance game I play[ed] or not)
1095 // - from remote peer (one live game I don't play, finished or not)
1096 fetchGame: function(callback) {
1097 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1098 // corr games identifiers are integers
1103 data: { gid: this.gameRef },
1105 res.game.moves.forEach(m => {
1106 m.squares = JSON.parse(m.squares);
1113 // Local game (or live remote)
1114 GameStorage.get(this.gameRef, callback);
1116 re_setClocks: function() {
1117 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1118 if (this.game.moves.length < 2 || this.game.score != "*") {
1119 // 1st move not completed yet, or game over: freeze time
1122 const currentTurn = this.vr.turn;
1123 const currentMovesCount = this.game.moves.length;
1124 const colorIdx = ["w", "b"].indexOf(currentTurn);
1125 this.clockUpdate = setInterval(
1128 this.game.clocks[colorIdx] < 0 ||
1129 this.game.moves.length > currentMovesCount ||
1130 this.game.score != "*"
1132 clearInterval(this.clockUpdate);
1133 this.clockUpdate = null;
1134 if (this.game.clocks[colorIdx] < 0)
1136 currentTurn == "w" ? "0-1" : "1-0",
1143 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1150 // Update variables and storage after a move:
1151 processMove: function(move, data) {
1152 if (!data) data = {};
1153 const moveCol = this.vr.turn;
1154 const colorIdx = ["w", "b"].indexOf(moveCol);
1155 const nextIdx = 1 - colorIdx;
1156 const doProcessMove = () => {
1157 const origMovescount = this.game.moves.length;
1158 // The move is (about to be) played: stop clock
1159 clearInterval(this.clockUpdate);
1160 this.clockUpdate = null;
1161 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1162 if (this.drawOffer == "received")
1164 this.drawOffer = "";
1165 if (this.game.type == "live" && origMovescount >= 2) {
1166 this.game.clocks[colorIdx] += this.game.increment;
1167 // For a correct display in casqe of disconnected opponent:
1171 ppt(this.game.clocks[colorIdx]).split(':')
1173 GameStorage.update(this.gameRef, {
1174 // It's not my turn anymore:
1179 // Update current game object:
1180 playMove(move, this.vr);
1182 // Received move, score is computed in BaseGame, but maybe not yet.
1183 // ==> Compute it here, although this is redundant (TODO)
1184 data.score = this.vr.getCurrentScore();
1185 if (data.score != "*") this.gameOver(data.score);
1186 this.game.moves.push(move);
1187 this.game.fen = this.vr.getFen();
1188 if (this.game.type == "corr") {
1189 // In corr games, just reset clock to mainTime:
1190 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1192 // If repetition detected, consider that a draw offer was received:
1193 const fenObj = this.vr.getFenForRepeat();
1194 this.repeat[fenObj] =
1195 !!this.repeat[fenObj]
1196 ? this.repeat[fenObj] + 1
1198 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1199 else if (this.drawOffer == "threerep") this.drawOffer = "";
1200 if (!!this.game.mycolor && !data.receiveMyMove) {
1201 // NOTE: 'var' to see that variable outside this block
1202 var filtered_move = getFilteredMove(move);
1204 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1205 // Notify turn on MyGames page:
1214 // Since corr games are stored at only one location, update should be
1215 // done only by one player for each move:
1217 this.game.type == "live" &&
1218 !!this.game.mycolor &&
1219 moveCol != this.game.mycolor &&
1220 this.game.moves.length >= 2
1222 // Receive a move: update initime
1223 this.game.initime = Date.now();
1224 GameStorage.update(this.gameRef, {
1225 // It's my turn now!
1226 initime: this.game.initime
1230 !!this.game.mycolor &&
1231 !data.receiveMyMove &&
1232 (this.game.type == "live" || moveCol == this.game.mycolor)
1235 switch (this.drawOffer) {
1240 drawCode = this.game.mycolor;
1243 drawCode = V.GetOppCol(this.game.mycolor);
1246 if (this.game.type == "corr") {
1247 // corr: only move, fen and score
1248 this.updateCorrGame({
1251 squares: filtered_move,
1254 // Code "n" for "None" to force reset (otherwise it's ignored)
1255 drawOffer: drawCode || "n"
1259 const updateStorage = () => {
1260 GameStorage.update(this.gameRef, {
1262 move: filtered_move,
1263 moveIdx: origMovescount,
1264 clocks: this.game.clocks,
1268 // The active tab can update storage immediately
1269 if (!document.hidden) updateStorage();
1270 // Small random delay otherwise
1271 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1274 // Send move ("newmove" event) to people in the room (if our turn)
1275 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1277 move: filtered_move,
1278 index: origMovescount,
1279 // color is required to check if this is my move (if several tabs opened)
1281 cancelDrawOffer: this.drawOffer == ""
1283 if (this.game.type == "live")
1284 sendMove["clock"] = this.game.clocks[colorIdx];
1285 // (Live) Clocks will re-start when the opponent pingback arrive
1286 this.opponentGotMove = false;
1287 this.send("newmove", {data: sendMove});
1288 // If the opponent doesn't reply gotmove soon enough, re-send move:
1289 // Do this at most 2 times, because mpore would mean network issues,
1290 // opponent would then be expected to disconnect/reconnect.
1292 const currentUrl = document.location.href;
1293 this.retrySendmove = setInterval(
1297 this.opponentGotMove ||
1298 document.location.href != currentUrl //page change
1300 clearInterval(this.retrySendmove);
1303 const oppsid = this.getOppsid();
1305 // Opponent is disconnected: he'll ask last state
1306 clearInterval(this.retrySendmove);
1308 this.send("newmove", { data: sendMove, target: oppsid });
1316 // Not my move or I'm an observer: just start other player's clock
1317 this.re_setClocks();
1320 this.game.type == "corr" &&
1321 moveCol == this.game.mycolor &&
1324 let boardDiv = document.querySelector(".game");
1325 const afterSetScore = () => {
1327 if (this.st.settings.gotonext && this.nextIds.length > 0)
1328 this.showNextGame();
1330 // The board might have been hidden:
1331 if (boardDiv.style.visibility == "hidden")
1332 boardDiv.style.visibility = "visible";
1333 if (data.score == "*") this.re_setClocks();
1336 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1337 // We may play several moves in a row: in case of, remove listener:
1338 let elClone = el.cloneNode(true);
1339 el.parentNode.replaceChild(elClone, el);
1340 elClone.addEventListener(
1343 document.getElementById("modalConfirm").checked = false;
1344 if (!!data.score && data.score != "*")
1346 this.gameOver(data.score, null, afterSetScore);
1347 else afterSetScore();
1350 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1351 V.PlayOnBoard(this.vr.board, move);
1352 const position = this.vr.getBaseFen();
1353 V.UndoOnBoard(this.vr.board, move);
1354 if (["all","byrow"].includes(V.ShowMoves)) {
1355 this.curDiag = getDiagram({
1357 orientation: V.CanFlip ? this.game.mycolor : "w"
1359 document.querySelector("#confirmDiv > .card").style.width =
1360 boardDiv.offsetWidth + "px";
1362 // Incomplete information: just ask confirmation
1363 // Hide the board, because otherwise it could reveal infos
1364 boardDiv.style.visibility = "hidden";
1365 this.moveNotation = getFullNotation(move);
1367 document.getElementById("modalConfirm").checked = true;
1371 if (!!data.score && data.score != "*")
1372 this.gameOver(data.score, null, doProcessMove);
1373 else doProcessMove();
1376 cancelMove: function() {
1377 let boardDiv = document.querySelector(".game");
1378 if (boardDiv.style.visibility == "hidden")
1379 boardDiv.style.visibility = "visible";
1380 document.getElementById("modalConfirm").checked = false;
1381 this.$refs["basegame"].cancelLastMove();
1383 // In corr games, callback to change page only after score is set:
1384 gameOver: function(score, scoreMsg, callback) {
1385 this.game.score = score;
1386 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1387 this.game.scoreMsg = scoreMsg;
1388 this.$set(this.game, "scoreMsg", scoreMsg);
1389 const myIdx = this.game.players.findIndex(p => {
1390 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1393 // OK, I play in this game
1398 if (this.game.type == "live") {
1399 GameStorage.update(this.gameRef, scoreObj);
1400 if (!!callback) callback();
1402 else this.updateCorrGame(scoreObj, callback);
1403 // Notify the score to main Hall. TODO: only one player (currently double send)
1404 this.send("result", { gid: this.game.id, score: score });
1405 // Also to MyGames page (TODO: doubled as well...)
1414 else if (!!callback) callback();
1420 <style lang="sass" scoped>
1426 background-color: lightgreen
1438 @media screen and (min-width: 768px)
1441 @media screen and (max-width: 767px)
1446 display: inline-block
1450 display: inline-block
1452 display: inline-flex
1456 @media screen and (max-width: 767px)
1459 @media screen and (max-width: 767px)
1462 @media screen and (min-width: 768px)
1474 background-color: #edda99
1476 display: inline-block
1485 display: inline-block
1498 animation: blink-animation 2s steps(3, start) infinite
1499 @keyframes blink-animation
1504 display: inline-block
1516 .draw-sent, .draw-sent:hover
1517 background-color: lightyellow
1519 .draw-received, .draw-received:hover
1520 background-color: lightgreen
1522 .draw-threerep, .draw-threerep:hover
1523 background-color: #e4d1fc
1525 .rematch-sent, .rematch-sent:hover
1526 background-color: lightyellow
1528 .rematch-received, .rematch-received:hover
1529 background-color: lightgreen
1532 background-color: #c5fefe
1545 background-color: lightgreen
1547 background-color: red