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="p.focus && !!p.name"
33 v-if="Object.values(people).some(p => p.focus && !p.name)"
38 :players="game.players"
39 :pastChats="game.chats"
41 @chatcleared="clearChat"
43 input#modalConfirm.modal(type="checkbox")
44 div#confirmDiv(role="dialog")
47 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
51 span {{ st.tr["Move played:"] + " " }}
52 span.bold {{ moveNotation }}
54 span {{ st.tr["Are you sure?"] }}
55 .button-group#buttonsConfirm
56 // onClick for acceptBtn: set dynamically
58 span {{ st.tr["Validate"] }}
59 button.refuseBtn(@click="cancelMove()")
60 span {{ st.tr["Cancel"] }}
62 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
63 span.variant-cadence {{ game.cadence }}
64 span.variant-name {{ game.vname }}
66 v-if="nextIds.length > 0"
67 @click="showNextGame()"
69 | {{ st.tr["Next_g"] }}
70 button#chatBtn.tooltip(
71 onClick="window.doClick('modalChat')"
74 img(src="/images/icons/chat.svg")
75 #actions(v-if="game.score=='*'")
78 :class="{['draw-' + drawOffer]: true}"
79 :aria-label="st.tr['Draw']"
81 img(src="/images/icons/draw.svg")
85 :aria-label="st.tr['Abort']"
87 img(src="/images/icons/abort.svg")
91 :aria-label="st.tr['Resign']"
93 img(src="/images/icons/resign.svg")
96 @click="clickRematch()"
97 :class="{['rematch-' + rematchOffer]: true}"
98 :aria-label="st.tr['Rematch']"
100 img(src="/images/icons/rematch.svg")
103 span.name(:class="{connected: isConnected(0)}")
104 | {{ game.players[0].name || "@nonymous" }}
106 v-if="game.score=='*'"
107 :class="{yourturn: !!vr && vr.turn == 'w'}"
109 span.time-left {{ virtualClocks[0][0] }}
110 span.time-separator(v-if="!!virtualClocks[0][1]") :
111 span.time-right(v-if="!!virtualClocks[0][1]")
112 | {{ virtualClocks[0][1] }}
114 span.name(:class="{connected: isConnected(1)}")
115 | {{ game.players[1].name || "@nonymous" }}
117 v-if="game.score=='*'"
118 :class="{yourturn: !!vr && vr.turn == 'b'}"
120 span.time-left {{ virtualClocks[1][0] }}
121 span.time-separator(v-if="!!virtualClocks[1][1]") :
122 span.time-right(v-if="!!virtualClocks[1][1]")
123 | {{ virtualClocks[1][1] }}
127 @newmove="processMove"
132 import BaseGame from "@/components/BaseGame.vue";
133 import Chat from "@/components/Chat.vue";
134 import { store } from "@/store";
135 import { GameStorage } from "@/utils/gameStorage";
136 import { ppt } from "@/utils/datetime";
137 import { ajax } from "@/utils/ajax";
138 import { extractTime } from "@/utils/timeControl";
139 import { getRandString } from "@/utils/alea";
140 import { getScoreMessage } from "@/utils/scoring";
141 import { getFullNotation } from "@/utils/notation";
142 import { getDiagram } from "@/utils/printDiagram";
143 import { processModalClick } from "@/utils/modalClick";
144 import { playMove, getFilteredMove } from "@/utils/playUndo";
145 import { ArrayFun } from "@/utils/array";
146 import params from "@/parameters";
156 // gameRef can point to a corr game, local game or remote live game
159 game: {}, //passed to BaseGame
160 // virtualClocks will be initialized from true game.clocks
162 vr: null, //"variant rules" object initialized from FEN
167 people: {}, //players + observers
168 lastate: undefined, //used if opponent send lastate before game is ready
169 repeat: {}, //detect position repetition
170 curDiag: "", //for corr moves confirmation
172 roomInitialized: false,
173 // If newmove has wrong index: ask fullgame again:
175 gameIsLoading: false,
176 // If asklastate got no reply, ask again:
178 gotMoveIdx: -1, //last move index received
179 // If newmove got no pingback, send again:
180 opponentGotMove: false,
182 // Incomplete info games: show move played
184 // Intervals from setInterval():
188 // Related to (killing of) self multi-connects:
194 $route: function(to, from) {
195 if (to.path.length < 6 || to.path.substr(6) != "/game/")
197 this.cleanBeforeDestroy();
198 else if (from.params["id"] != to.params["id"]) {
199 // Change everything:
200 this.cleanBeforeDestroy();
201 let boardDiv = document.querySelector(".game");
203 // In case of incomplete information variant:
204 boardDiv.style.visibility = "hidden";
208 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
211 // NOTE: some redundant code with Hall.vue (mostly related to people array)
212 created: function() {
215 mounted: function() {
216 ["chatWrap", "infoDiv"].forEach(eltName => {
217 document.getElementById(eltName)
218 .addEventListener("click", processModalClick);
220 if ("ontouchstart" in window) {
221 // Disable tooltips on smartphones:
222 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
223 elt.classList.remove("tooltip");
227 beforeDestroy: function() {
228 this.cleanBeforeDestroy();
231 cleanBeforeDestroy: function() {
232 document.removeEventListener('visibilitychange', this.visibilityChange);
233 if (!!this.askLastate)
234 clearInterval(this.askLastate);
235 if (!!this.retrySendmove)
236 clearInterval(this.retrySendmove);
237 if (!!this.clockUpdate)
238 clearInterval(this.clockUpdate);
239 this.send("disconnect");
241 visibilityChange: function() {
242 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
244 document.visibilityState == "visible"
249 atCreation: function() {
250 document.addEventListener('visibilitychange', this.visibilityChange);
251 // 0] (Re)Set variables
252 this.gameRef = this.$route.params["id"];
253 // next = next corr games IDs to navigate faster (if applicable)
254 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
255 // Always add myself to players' list
256 const my = this.st.user;
267 players: [{ name: "" }, { name: "" }],
271 let chatComp = this.$refs["chatcomp"];
272 if (!!chatComp) chatComp.chats = [];
273 this.virtualClocks = [[0,0], [0,0]];
276 this.lastateAsked = false;
277 this.rematchOffer = "";
278 this.lastate = undefined;
279 this.roomInitialized = false;
280 this.askGameTime = 0;
281 this.gameIsLoading = false;
282 this.gotLastate = false;
283 this.gotMoveIdx = -1;
284 this.opponentGotMove = false;
285 this.askLastate = null;
286 this.retrySendmove = null;
287 this.clockUpdate = null;
288 this.newConnect = {};
290 // 1] Initialize connection
291 this.connexionString =
300 // Discard potential "/?next=[...]" for page indication:
301 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
302 this.conn = new WebSocket(this.connexionString);
303 this.conn.addEventListener("message", this.socketMessageListener);
304 this.conn.addEventListener("close", this.socketCloseListener);
305 // Socket init required before loading remote game:
306 const socketInit = callback => {
307 if (this.conn.readyState == 1)
311 // Socket not ready yet (initial loading)
312 // NOTE: first arg is Websocket object, unused here:
313 this.conn.onopen = () => callback();
315 this.fetchGame((game) => {
317 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
319 // Live game stored remotely: need socket to retrieve it
320 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
321 // --> It will be given when receiving "fullgame" socket event.
322 socketInit(() => { this.send("askfullgame"); });
325 roomInit: function() {
326 if (!this.roomInitialized) {
327 // Notify the room only now that I connected, because
328 // messages might be lost otherwise (if game loading is slow)
329 this.send("connect");
330 this.send("pollclients");
331 // We may ask fullgame several times if some moves are lost,
332 // but room should be init only once:
333 this.roomInitialized = true;
336 send: function(code, obj) {
338 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
340 isConnected: function(index) {
341 const player = this.game.players[index];
342 // Is it me ? In this case no need to bother with focus
343 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
344 // Still have to check for name (because of potential multi-accounts
345 // on same browser, although this should be rare...)
346 return (!this.st.user.name || this.st.user.name == player.name);
347 // Try to find a match in people:
351 Object.keys(this.people).some(sid =>
352 sid == player.sid && this.people[sid].focus)
357 Object.values(this.people).some(p =>
358 p.id == player.id && p.focus)
362 getOppsid: function() {
363 let oppsid = this.game.oppsid;
365 oppsid = Object.keys(this.people).find(
366 sid => this.people[sid].id == this.game.oppid
369 // oppsid is useful only if opponent is online:
370 if (!!oppsid && !!this.people[oppsid]) return oppsid;
373 toggleChat: function() {
374 if (document.getElementById("modalChat").checked)
376 document.getElementById("inputChat").focus();
377 // TODO: next line is only required when exiting chat,
378 // but the event for now isn't well detected.
379 document.getElementById("chatBtn").classList.remove("somethingnew");
381 processChat: function(chat) {
382 this.send("newchat", { data: chat });
383 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
384 if (this.game.type == "corr" && this.st.user.id > 0)
385 this.updateCorrGame({ chat: chat });
387 clearChat: function() {
388 // Nothing more to do if game is live (chats not recorded)
389 if (this.game.type == "corr") {
390 if (!!this.game.mycolor) {
394 { data: { gid: this.game.id } }
397 this.$set(this.game, "chats", []);
400 getGameType: function(game) {
401 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
403 // Notify something after a new move (to opponent and me on MyGames page)
404 notifyMyGames: function(thing, data) {
409 targets: this.game.players.map(p => {
410 return { sid: p.sid, id: p.id };
415 showNextGame: function() {
416 // Did I play in current game? If not, add it to nextIds list
417 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
418 this.nextIds.unshift(this.game.id);
419 const nextGid = this.nextIds.pop();
421 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
423 askGameAgain: function() {
424 this.gameIsLoading = true;
425 const currentUrl = document.location.href;
426 const doAskGame = () => {
427 if (document.location.href != currentUrl) return; //page change
428 this.fetchGame((game) => {
430 // This is my game: just reload.
433 // Just ask fullgame again (once!), this is much simpler.
434 // If this fails, the user could just reload page :/
435 this.send("askfullgame");
438 // Delay of at least 2s between two game requests
439 const now = Date.now();
440 const delay = Math.max(2000 - (now - this.askGameTime), 0);
441 this.askGameTime = now;
442 setTimeout(doAskGame, delay);
444 socketMessageListener: function(msg) {
445 if (!this.conn) return;
446 const data = JSON.parse(msg.data);
449 // TODO: shuffling and random filtering on server, if
450 // the room is really crowded.
451 data.sockIds.forEach(sid => {
452 if (sid != this.st.user.sid) {
453 this.people[sid] = { focus: true };
454 this.send("askidentity", { target: sid });
459 if (!this.people[data.from]) {
460 this.people[data.from] = { focus: true };
461 this.$forceUpdate(); //TODO: shouldn't be required
462 this.newConnect[data.from] = true; //for self multi-connects tests
463 this.send("askidentity", { target: data.from });
467 this.$delete(this.people, data.from);
470 let player = this.people[data.from];
473 this.$forceUpdate(); //TODO: shouldn't be required
478 let player = this.people[data.from];
480 player.focus = false;
481 this.$forceUpdate(); //TODO: shouldn't be required
486 // I logged in elsewhere:
487 this.conn.removeEventListener("message", this.socketMessageListener);
488 this.conn.removeEventListener("close", this.socketCloseListener);
490 alert(this.st.tr["New connexion detected: tab now offline"]);
492 case "askidentity": {
493 // Request for identification
495 // Decompose to avoid revealing email
496 name: this.st.user.name,
497 sid: this.st.user.sid,
500 this.send("identity", { data: me, target: data.from });
504 const user = data.data;
505 let player = this.people[user.sid];
506 // player.focus is already set
507 player.name = user.name;
509 this.$forceUpdate(); //TODO: shouldn't be required
510 // If I multi-connect, kill current connexion if no mark (I'm older)
511 if (this.newConnect[user.sid]) {
514 user.id == this.st.user.id &&
515 user.sid != this.st.user.sid &&
516 !this.killed[this.st.user.sid]
518 this.send("killme", { sid: this.st.user.sid });
519 this.killed[this.st.user.sid] = true;
521 delete this.newConnect[user.sid];
523 if (!this.killed[this.st.user.sid]) {
524 // Ask potentially missed last state, if opponent and I play
527 !!this.game.mycolor &&
528 this.game.type == "live" &&
529 this.game.score == "*" &&
530 this.game.players.some(p => p.sid == user.sid)
532 this.send("asklastate", { target: user.sid });
534 this.askLastate = setInterval(
536 // Ask at most 3 times:
537 // if no reply after that there should be a network issue.
541 !!this.people[user.sid]
543 this.send("asklastate", { target: user.sid });
546 clearInterval(this.askLastate);
556 // Send current (live) game if not asked by any of the players
558 this.game.type == "live" &&
559 this.game.players.every(p => p.sid != data.from[0])
564 players: this.game.players,
566 cadence: this.game.cadence,
567 score: this.game.score
569 this.send("game", { data: myGame, target: data.from });
573 const gameToSend = Object.keys(this.game)
576 "id","fen","players","vid","cadence","fenStart","vname",
577 "moves","clocks","score","drawOffer","rematchOffer"
581 obj[k] = this.game[k];
586 this.send("fullgame", { data: gameToSend, target: data.from });
589 // Callback "roomInit" to poll clients only after game is loaded
590 this.loadVariantThenGame(data.data, this.roomInit);
593 // Sending informative last state if I played a move or score != "*"
594 // If the game or moves aren't loaded yet, delay the sending:
595 if (!this.game || !this.game.moves) this.lastateAsked = true;
596 else this.sendLastate(data.from);
599 // Got opponent infos about last move
600 this.gotLastate = true;
601 this.lastate = data.data;
602 if (this.game.rendered)
603 // Game is rendered (Board component)
604 this.processLastate();
605 // Else: will be processed when game is ready
609 const movePlus = data.data;
610 const movesCount = this.game.moves.length;
611 if (movePlus.index > movesCount) {
612 // This can only happen if I'm an observer and missed a move.
613 if (this.gotMoveIdx < movePlus.index)
614 this.gotMoveIdx = movePlus.index;
615 if (!this.gameIsLoading) this.askGameAgain();
619 movePlus.index < movesCount ||
620 this.gotMoveIdx >= movePlus.index
622 // Opponent re-send but we already have the move:
623 // (maybe he didn't receive our pingback...)
624 this.send("gotmove", {data: movePlus.index, target: data.from});
626 this.gotMoveIdx = movePlus.index;
627 const receiveMyMove = (movePlus.color == this.game.mycolor);
628 if (!receiveMyMove && !!this.game.mycolor)
629 // Notify opponent that I got the move:
630 this.send("gotmove", {data: movePlus.index, target: data.from});
631 if (movePlus.cancelDrawOffer) {
632 // Opponent refuses draw
634 // NOTE for corr games: drawOffer reset by player in turn
636 this.game.type == "live" &&
637 !!this.game.mycolor &&
640 GameStorage.update(this.gameRef, { drawOffer: "" });
643 this.$refs["basegame"].play(movePlus.move, "received", null, true);
644 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
645 this.game.clocks[moveColIdx] = movePlus.clock;
648 { receiveMyMove: receiveMyMove }
655 this.opponentGotMove = true;
656 // Now his clock starts running on my side:
657 const oppIdx = ['w','b'].indexOf(this.vr.turn);
662 const score = (data.data == "b" ? "1-0" : "0-1");
663 const side = (data.data == "w" ? "White" : "Black");
664 this.gameOver(score, side + " surrender");
667 this.gameOver("?", "Stop");
670 this.gameOver("1/2", data.data);
673 // NOTE: observers don't know who offered draw
674 this.drawOffer = "received";
675 if (this.game.type == "live") {
678 { drawOffer: V.GetOppCol(this.game.mycolor) }
683 // NOTE: observers don't know who offered rematch
684 this.rematchOffer = data.data ? "received" : "";
685 if (this.game.type == "live") {
688 { rematchOffer: V.GetOppCol(this.game.mycolor) }
693 // A game started, redirect if I'm playing in
694 const gameInfo = data.data;
695 const gameType = this.getGameType(gameInfo);
697 gameType == "live" &&
698 gameInfo.players.some(p => p.sid == this.st.user.sid)
700 this.addAndGotoLiveGame(gameInfo);
702 gameType == "corr" &&
703 gameInfo.players.some(p => p.id == this.st.user.id)
705 this.$router.push("/game/" + gameInfo.id);
707 this.rematchId = gameInfo.id;
708 document.getElementById("modalInfo").checked = true;
713 this.$refs["chatcomp"].newChat(data.data);
714 if (!document.getElementById("modalChat").checked)
715 document.getElementById("chatBtn").classList.add("somethingnew");
719 socketCloseListener: function() {
720 this.conn = new WebSocket(this.connexionString);
721 this.conn.addEventListener("message", this.socketMessageListener);
722 this.conn.addEventListener("close", this.socketCloseListener);
724 updateCorrGame: function(obj, callback) {
734 if (!!callback) callback();
739 sendLastate: function(target) {
740 // Send our "last state" informations to opponent
741 const L = this.game.moves.length;
742 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
745 (L > 0 && this.vr.turn != this.game.mycolor)
746 ? this.game.moves[L - 1]
748 clock: this.game.clocks[myIdx],
749 // Since we played a move (or abort or resign),
750 // only drawOffer=="sent" is possible
751 drawSent: this.drawOffer == "sent",
752 rematchSent: this.rematchOffer == "sent",
753 score: this.game.score != "*" ? this.game.score : undefined,
754 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
757 this.send("lastate", { data: myLastate, target: target });
759 // lastate was received, but maybe game wasn't ready yet:
760 processLastate: function() {
761 const data = this.lastate;
762 this.lastate = undefined; //security...
763 const L = this.game.moves.length;
764 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
765 this.game.clocks[oppIdx] = data.clock;
766 if (data.movesCount > L) {
767 // Just got last move from him
768 this.$refs["basegame"].play(data.lastMove, "received", null, true);
769 this.processMove(data.lastMove);
771 clearInterval(this.clockUpdate);
774 if (data.drawSent) this.drawOffer = "received";
775 if (data.rematchSent) this.rematchOffer = "received";
778 if (this.game.score == "*")
779 this.gameOver(data.score, data.scoreMsg);
782 clickDraw: function() {
783 if (!this.game.mycolor) return; //I'm just spectator
784 if (["received", "threerep"].includes(this.drawOffer)) {
785 if (!confirm(this.st.tr["Accept draw?"])) return;
787 this.drawOffer == "received"
789 : "Three repetitions";
790 this.send("draw", { data: message });
791 this.gameOver("1/2", message);
792 } else if (this.drawOffer == "") {
793 // No effect if drawOffer == "sent"
794 if (this.game.mycolor != this.vr.turn) {
795 alert(this.st.tr["Draw offer only in your turn"]);
798 if (!confirm(this.st.tr["Offer draw?"])) return;
799 this.drawOffer = "sent";
800 this.send("drawoffer");
801 if (this.game.type == "live") {
804 { drawOffer: this.game.mycolor }
806 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
809 addAndGotoLiveGame: function(gameInfo, callback) {
810 const game = Object.assign(
814 // (other) Game infos: constant
815 fenStart: gameInfo.fen,
816 vname: this.game.vname,
818 // Game state (including FEN): will be updated
820 clocks: [-1, -1], //-1 = unstarted
824 GameStorage.add(game, (err) => {
825 // No error expected.
827 if (this.st.settings.sound)
828 new Audio("/sounds/newgame.flac").play().catch(() => {});
829 if (!!callback) callback();
830 this.$router.push("/game/" + gameInfo.id);
834 clickRematch: function() {
835 if (!this.game.mycolor) return; //I'm just spectator
836 if (this.rematchOffer == "received") {
839 id: getRandString(), //ignored if corr
840 fen: V.GenRandInitFen(this.game.randomness),
841 players: this.game.players.reverse(),
843 cadence: this.game.cadence
845 const notifyNewGame = () => {
846 const oppsid = this.getOppsid(); //may be null
847 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
848 // To main Hall if corr game:
849 if (this.game.type == "corr")
850 this.send("newgame", { data: gameInfo });
851 // Also to MyGames page:
852 this.notifyMyGames("newgame", gameInfo);
854 if (this.game.type == "live")
855 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
862 // cid is useful to delete the challenge:
863 data: { gameInfo: gameInfo },
864 success: (response) => {
865 gameInfo.id = response.gameId;
867 this.$router.push("/game/" + response.gameId);
872 } else if (this.rematchOffer == "") {
873 this.rematchOffer = "sent";
874 this.send("rematchoffer", { data: true });
875 if (this.game.type == "live") {
878 { rematchOffer: this.game.mycolor }
880 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
881 } else if (this.rematchOffer == "sent") {
882 // Toggle rematch offer (on --> off)
883 this.rematchOffer = "";
884 this.send("rematchoffer", { data: false });
885 if (this.game.type == "live") {
890 } else this.updateCorrGame({ rematchOffer: 'n' });
893 abortGame: function() {
894 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
895 this.gameOver("?", "Stop");
899 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
901 this.send("resign", { data: this.game.mycolor });
902 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
903 const side = (this.game.mycolor == "w" ? "White" : "Black");
904 this.gameOver(score, side + " surrender");
906 loadGame: function(game, callback) {
907 this.vr = new V(game.fen);
908 const gtype = this.getGameType(game);
909 const tc = extractTime(game.cadence);
910 const myIdx = game.players.findIndex(p => {
911 return p.sid == this.st.user.sid || p.id == this.st.user.id;
913 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
914 if (!game.chats) game.chats = []; //live games don't have chat history
915 if (gtype == "corr") {
916 // NOTE: clocks in seconds
917 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
918 game.clocks = [tc.mainTime, tc.mainTime];
919 const L = game.moves.length;
920 if (game.score == "*") {
923 game.clocks[L % 2] -=
924 (Date.now() - game.moves[L-1].played) / 1000;
927 // Sort chat messages from newest to oldest
928 game.chats.sort((c1, c2) => {
929 return c2.added - c1.added;
931 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
932 // Did a chat message arrive after my last move?
934 if (L == 1 && myIdx == 0)
935 dtLastMove = game.moves[0].played;
938 // It's now white turn
939 dtLastMove = game.moves[L-1-(1-myIdx)].played;
942 dtLastMove = game.moves[L-1-myIdx].played;
945 if (dtLastMove < game.chats[0].added)
946 document.getElementById("chatBtn").classList.add("somethingnew");
948 // Now that we used idx and played, re-format moves as for live games
949 game.moves = game.moves.map(m => m.squares);
951 if (gtype == "live") {
952 if (game.clocks[0] < 0) {
953 // Game is unstarted. clock is ignored until move 2
954 game.clocks = [tc.mainTime, tc.mainTime];
956 // I play in this live game
957 GameStorage.update(game.id, {
963 // It's my turn: clocks not updated yet
964 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
967 // TODO: merge next 2 "if" conditions
968 if (!!game.drawOffer) {
969 if (game.drawOffer == "t")
971 this.drawOffer = "threerep";
973 // Draw offered by any of the players:
974 if (myIdx < 0) this.drawOffer = "received";
976 // I play in this game:
978 (game.drawOffer == "w" && myIdx == 0) ||
979 (game.drawOffer == "b" && myIdx == 1)
981 this.drawOffer = "sent";
982 else this.drawOffer = "received";
986 if (!!game.rematchOffer) {
987 if (myIdx < 0) this.rematchOffer = "received";
989 // I play in this game:
991 (game.rematchOffer == "w" && myIdx == 0) ||
992 (game.rematchOffer == "b" && myIdx == 1)
994 this.rematchOffer = "sent";
995 else this.rematchOffer = "received";
998 this.repeat = {}; //reset: scan past moves' FEN:
1000 let vr_tmp = new V(game.fenStart);
1002 game.moves.forEach(m => {
1003 playMove(m, vr_tmp);
1004 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1005 this.repeat[fenIdx] = this.repeat[fenIdx]
1006 ? this.repeat[fenIdx] + 1
1009 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1010 this.game = Object.assign(
1011 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1014 increment: tc.increment,
1016 // opponent sid not strictly required (or available), but easier
1017 // at least oppsid or oppid is available anyway:
1018 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1019 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1023 this.$refs["basegame"].re_setVariables(this.game);
1024 if (!this.gameIsLoading) {
1026 this.gotMoveIdx = game.moves.length - 1;
1027 // If we arrive here after 'nextGame' action, the board might be hidden
1028 let boardDiv = document.querySelector(".game");
1029 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1030 boardDiv.style.visibility = "visible";
1032 this.re_setClocks();
1033 this.$nextTick(() => {
1034 this.game.rendered = true;
1035 // Did lastate arrive before game was rendered?
1036 if (this.lastate) this.processLastate();
1038 if (this.lastateAsked) {
1039 this.lastateAsked = false;
1040 this.sendLastate(game.oppsid);
1042 if (this.gameIsLoading) {
1043 this.gameIsLoading = false;
1044 if (this.gotMoveIdx >= game.moves.length)
1045 // Some moves arrived meanwhile...
1046 this.askGameAgain();
1048 if (!!callback) callback();
1050 loadVariantThenGame: async function(game, callback) {
1051 await import("@/variants/" + game.vname + ".js")
1052 .then((vModule) => {
1053 window.V = vModule[game.vname + "Rules"];
1054 this.loadGame(game, callback);
1057 // 3 cases for loading a game:
1058 // - from indexedDB (running or completed live game I play)
1059 // - from server (one correspondance game I play[ed] or not)
1060 // - from remote peer (one live game I don't play, finished or not)
1061 fetchGame: function(callback) {
1062 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1063 // corr games identifiers are integers
1068 data: { gid: this.gameRef },
1070 res.game.moves.forEach(m => {
1071 m.squares = JSON.parse(m.squares);
1078 // Local game (or live remote)
1079 GameStorage.get(this.gameRef, callback);
1081 re_setClocks: function() {
1082 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1083 if (this.game.moves.length < 2 || this.game.score != "*") {
1084 // 1st move not completed yet, or game over: freeze time
1087 const currentTurn = this.vr.turn;
1088 const currentMovesCount = this.game.moves.length;
1089 const colorIdx = ["w", "b"].indexOf(currentTurn);
1090 this.clockUpdate = setInterval(
1093 this.game.clocks[colorIdx] < 0 ||
1094 this.game.moves.length > currentMovesCount ||
1095 this.game.score != "*"
1097 clearInterval(this.clockUpdate);
1098 if (this.game.clocks[colorIdx] < 0)
1100 currentTurn == "w" ? "0-1" : "1-0",
1107 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1114 // Update variables and storage after a move:
1115 processMove: function(move, data) {
1116 if (!data) data = {};
1117 const moveCol = this.vr.turn;
1118 const colorIdx = ["w", "b"].indexOf(moveCol);
1119 const nextIdx = 1 - colorIdx;
1120 const doProcessMove = () => {
1121 const origMovescount = this.game.moves.length;
1122 // The move is (about to be) played: stop clock
1123 clearInterval(this.clockUpdate);
1124 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1125 if (this.drawOffer == "received")
1127 this.drawOffer = "";
1128 if (this.game.type == "live" && origMovescount >= 2) {
1129 this.game.clocks[colorIdx] += this.game.increment;
1130 // For a correct display in casqe of disconnected opponent:
1134 ppt(this.game.clocks[colorIdx]).split(':')
1136 GameStorage.update(this.gameRef, {
1137 // It's not my turn anymore:
1142 // Update current game object:
1143 playMove(move, this.vr);
1145 // Received move, score is computed in BaseGame, but maybe not yet.
1146 // ==> Compute it here, although this is redundant (TODO)
1147 data.score = this.vr.getCurrentScore();
1148 if (data.score != "*") this.gameOver(data.score);
1149 this.game.moves.push(move);
1150 this.game.fen = this.vr.getFen();
1151 if (this.game.type == "corr") {
1152 // In corr games, just reset clock to mainTime:
1153 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1155 // If repetition detected, consider that a draw offer was received:
1156 const fenObj = this.vr.getFenForRepeat();
1157 this.repeat[fenObj] =
1158 !!this.repeat[fenObj]
1159 ? this.repeat[fenObj] + 1
1161 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1162 else if (this.drawOffer == "threerep") this.drawOffer = "";
1163 if (!!this.game.mycolor && !data.receiveMyMove) {
1164 // NOTE: 'var' to see that variable outside this block
1165 var filtered_move = getFilteredMove(move);
1167 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1168 // Notify turn on MyGames page:
1177 // Since corr games are stored at only one location, update should be
1178 // done only by one player for each move:
1180 this.game.type == "live" &&
1181 !!this.game.mycolor &&
1182 moveCol != this.game.mycolor &&
1183 this.game.moves.length >= 2
1185 // Receive a move: update initime
1186 this.game.initime = Date.now();
1187 GameStorage.update(this.gameRef, {
1188 // It's my turn now!
1189 initime: this.game.initime
1193 !!this.game.mycolor &&
1194 !data.receiveMyMove &&
1195 (this.game.type == "live" || moveCol == this.game.mycolor)
1198 switch (this.drawOffer) {
1203 drawCode = this.game.mycolor;
1206 drawCode = V.GetOppCol(this.game.mycolor);
1209 if (this.game.type == "corr") {
1210 // corr: only move, fen and score
1211 this.updateCorrGame({
1214 squares: filtered_move,
1217 // Code "n" for "None" to force reset (otherwise it's ignored)
1218 drawOffer: drawCode || "n"
1222 const updateStorage = () => {
1223 GameStorage.update(this.gameRef, {
1225 move: filtered_move,
1226 moveIdx: origMovescount,
1227 clocks: this.game.clocks,
1231 // The active tab can update storage immediately
1232 if (!document.hidden) updateStorage();
1233 // Small random delay otherwise
1234 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1237 // Send move ("newmove" event) to people in the room (if our turn)
1238 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1240 move: filtered_move,
1241 index: origMovescount,
1242 // color is required to check if this is my move (if several tabs opened)
1244 cancelDrawOffer: this.drawOffer == ""
1246 if (this.game.type == "live")
1247 sendMove["clock"] = this.game.clocks[colorIdx];
1248 // (Live) Clocks will re-start when the opponent pingback arrive
1249 this.opponentGotMove = false;
1250 this.send("newmove", {data: sendMove});
1251 // If the opponent doesn't reply gotmove soon enough, re-send move:
1252 // Do this at most 2 times, because mpore would mean network issues,
1253 // opponent would then be expected to disconnect/reconnect.
1255 const currentUrl = document.location.href;
1256 this.retrySendmove = setInterval(
1260 this.opponentGotMove ||
1261 document.location.href != currentUrl //page change
1263 clearInterval(this.retrySendmove);
1266 const oppsid = this.getOppsid();
1268 // Opponent is disconnected: he'll ask last state
1269 clearInterval(this.retrySendmove);
1271 this.send("newmove", { data: sendMove, target: oppsid });
1279 // Not my move or I'm an observer: just start other player's clock
1280 this.re_setClocks();
1283 this.game.type == "corr" &&
1284 moveCol == this.game.mycolor &&
1287 let boardDiv = document.querySelector(".game");
1288 const afterSetScore = () => {
1290 if (this.st.settings.gotonext && this.nextIds.length > 0)
1291 this.showNextGame();
1293 // The board might have been hidden:
1294 if (boardDiv.style.visibility == "hidden")
1295 boardDiv.style.visibility = "visible";
1296 if (data.score == "*") this.re_setClocks();
1299 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1300 // We may play several moves in a row: in case of, remove listener:
1301 let elClone = el.cloneNode(true);
1302 el.parentNode.replaceChild(elClone, el);
1303 elClone.addEventListener(
1306 document.getElementById("modalConfirm").checked = false;
1307 if (!!data.score && data.score != "*")
1309 this.gameOver(data.score, null, afterSetScore);
1310 else afterSetScore();
1313 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1314 V.PlayOnBoard(this.vr.board, move);
1315 const position = this.vr.getBaseFen();
1316 V.UndoOnBoard(this.vr.board, move);
1317 if (["all","byrow"].includes(V.ShowMoves)) {
1318 this.curDiag = getDiagram({
1320 orientation: V.CanFlip ? this.game.mycolor : "w"
1322 document.querySelector("#confirmDiv > .card").style.width =
1323 boardDiv.offsetWidth + "px";
1325 // Incomplete information: just ask confirmation
1326 // Hide the board, because otherwise it could reveal infos
1327 boardDiv.style.visibility = "hidden";
1328 this.moveNotation = getFullNotation(move);
1330 document.getElementById("modalConfirm").checked = true;
1334 if (!!data.score && data.score != "*")
1335 this.gameOver(data.score, null, doProcessMove);
1336 else doProcessMove();
1339 cancelMove: function() {
1340 let boardDiv = document.querySelector(".game");
1341 if (boardDiv.style.visibility == "hidden")
1342 boardDiv.style.visibility = "visible";
1343 document.getElementById("modalConfirm").checked = false;
1344 this.$refs["basegame"].cancelLastMove();
1346 // In corr games, callback to change page only after score is set:
1347 gameOver: function(score, scoreMsg, callback) {
1348 this.game.score = score;
1349 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1350 this.game.scoreMsg = scoreMsg;
1351 this.$set(this.game, "scoreMsg", scoreMsg);
1352 const myIdx = this.game.players.findIndex(p => {
1353 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1356 // OK, I play in this game
1361 if (this.game.type == "live") {
1362 GameStorage.update(this.gameRef, scoreObj);
1363 if (!!callback) callback();
1365 else this.updateCorrGame(scoreObj, callback);
1366 // Notify the score to main Hall. TODO: only one player (currently double send)
1367 this.send("result", { gid: this.game.id, score: score });
1368 // Also to MyGames page (TODO: doubled as well...)
1377 else if (!!callback) callback();
1383 <style lang="sass" scoped>
1389 background-color: lightgreen
1401 @media screen and (min-width: 768px)
1404 @media screen and (max-width: 767px)
1409 display: inline-block
1413 display: inline-block
1415 display: inline-flex
1419 @media screen and (max-width: 767px)
1422 @media screen and (max-width: 767px)
1425 @media screen and (min-width: 768px)
1437 background-color: #edda99
1439 display: inline-block
1448 display: inline-block
1461 animation: blink-animation 2s steps(3, start) infinite
1462 @keyframes blink-animation
1467 display: inline-block
1479 .draw-sent, .draw-sent:hover
1480 background-color: lightyellow
1482 .draw-received, .draw-received:hover
1483 background-color: lightgreen
1485 .draw-threerep, .draw-threerep:hover
1486 background-color: #e4d1fc
1488 .rematch-sent, .rematch-sent:hover
1489 background-color: lightyellow
1491 .rematch-received, .rematch-received:hover
1492 background-color: lightgreen
1495 background-color: #c5fefe
1508 background-color: lightgreen
1510 background-color: red