3 input#modalScore.modal(type="checkbox")
6 data-checkbox="modalScore"
9 label.modal-close(for="modalScore")
11 span.score {{ game.score }}
13 span.score-msg {{ st.tr[game.scoreMsg] }}
14 input#modalRematch.modal(type="checkbox")
17 data-checkbox="modalRematch"
20 label.modal-close(for="modalRematch")
22 :href="'#/game/' + rematchId"
23 onClick="document.getElementById('modalRematch').checked=false"
25 | {{ st.tr["Rematch in progress"] }}
26 input#modalChat.modal(
32 data-checkbox="modalChat"
35 label.modal-close(for="modalChat")
37 span {{ st.tr["Participant(s):"] }}
39 v-for="p in Object.values(people)"
40 v-if="participateInChat(p)"
43 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
46 :players="game.players"
47 :pastChats="game.chats"
49 @chatcleared="clearChat"
51 input#modalConfirm.modal(type="checkbox")
52 div#confirmDiv(role="dialog")
55 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
59 span {{ st.tr["Move played:"] + " " }}
60 span.bold {{ moveNotation }}
62 span {{ st.tr["Are you sure?"] }}
63 .button-group#buttonsConfirm
64 // onClick for acceptBtn: set dynamically
66 span {{ st.tr["Validate"] }}
67 button.refuseBtn(@click="cancelMove()")
68 span {{ st.tr["Cancel"] }}
70 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
71 span.variant-cadence(v-if="game.type!='import'") {{ game.cadence }}
72 span.variant-name {{ game.vname }}
74 v-if="nextIds.length > 0"
75 @click="showNextGame()"
77 | {{ st.tr["Next_g"] }}
78 button#chatBtn.tooltip(
79 onClick="window.doClick('modalChat')"
82 img(src="/images/icons/chat.svg")
83 #actions(v-if="game.score=='*'")
86 :class="{['draw-' + drawOffer]: true}"
87 :aria-label="st.tr['Draw']"
89 img(src="/images/icons/draw.svg")
93 :aria-label="st.tr['Abort']"
95 img(src="/images/icons/abort.svg")
99 :aria-label="st.tr['Resign']"
101 img(src="/images/icons/resign.svg")
104 @click="clickRematch()"
105 :class="{['rematch-' + rematchOffer]: true}"
106 :aria-label="st.tr['Rematch']"
108 img(src="/images/icons/rematch.svg")
110 p(v-if="isLargeScreen()")
111 span.name(:class="{connected: isConnected(0)}")
112 | {{ game.players[0].name || "@nonymous" }}
114 v-if="game.score=='*'"
115 :class="{yourturn: !!vr && vr.turn == 'w'}"
117 span.time-left {{ virtualClocks[0][0] }}
118 span.time-separator(v-if="!!virtualClocks[0][1]") :
119 span.time-right(v-if="!!virtualClocks[0][1]")
120 | {{ virtualClocks[0][1] }}
122 span.name(:class="{connected: isConnected(1)}")
123 | {{ game.players[1].name || "@nonymous" }}
125 v-if="game.score=='*'"
126 :class="{yourturn: !!vr && vr.turn == 'b'}"
128 span.time-left {{ virtualClocks[1][0] }}
129 span.time-separator(v-if="!!virtualClocks[1][1]") :
130 span.time-right(v-if="!!virtualClocks[1][1]")
131 | {{ virtualClocks[1][1] }}
133 span.name(:class="{connected: isConnected(0)}")
134 | {{ game.players[0].name || "@nonymous" }}
136 span.name(:class="{connected: isConnected(1)}")
137 | {{ game.players[1].name || "@nonymous" }}
140 v-if="game.score=='*'"
141 :class="{yourturn: !!vr && vr.turn == 'w'}"
143 span.time-left {{ virtualClocks[0][0] }}
144 span.time-separator(v-if="!!virtualClocks[0][1]") :
145 span.time-right(v-if="!!virtualClocks[0][1]")
146 | {{ virtualClocks[0][1] }}
148 v-if="game.score=='*'"
149 :class="{yourturn: !!vr && vr.turn == 'b'}"
151 span.time-left {{ virtualClocks[1][0] }}
152 span.time-separator(v-if="!!virtualClocks[1][1]") :
153 span.time-right(v-if="!!virtualClocks[1][1]")
154 | {{ virtualClocks[1][1] }}
158 @newmove="processMove"
163 import BaseGame from "@/components/BaseGame.vue";
164 import Chat from "@/components/Chat.vue";
165 import { store } from "@/store";
166 import { GameStorage } from "@/utils/gameStorage";
167 import { ImportgameStorage } from "@/utils/importgameStorage";
168 import { ppt } from "@/utils/datetime";
169 import { notify } from "@/utils/notifications";
170 import { ajax } from "@/utils/ajax";
171 import { extractTime } from "@/utils/timeControl";
172 import { getRandString } from "@/utils/alea";
173 import { getScoreMessage } from "@/utils/scoring";
174 import { getFullNotation } from "@/utils/notation";
175 import { getDiagram } from "@/utils/printDiagram";
176 import { processModalClick } from "@/utils/modalClick";
177 import { playMove, getFilteredMove } from "@/utils/playUndo";
178 import { ArrayFun } from "@/utils/array";
179 import params from "@/parameters";
189 // gameRef can point to a corr game, local game or remote live game
192 game: {}, //passed to BaseGame
193 focus: !document.hidden, //will not always work... TODO
194 // virtualClocks will be initialized from true game.clocks
196 vr: null, //"variant rules" object initialized from FEN
201 people: {}, //players + observers
202 lastate: undefined, //used if opponent send lastate before game is ready
203 repeat: {}, //detect position repetition
204 curDiag: "", //for corr moves confirmation
206 roomInitialized: false,
207 // If newmove has wrong index: ask fullgame again:
209 gameIsLoading: false,
210 // If asklastate got no reply, ask again:
212 gotMoveIdx: -1, //last move index received
213 // If newmove got no pingback, send again:
214 opponentGotMove: false,
216 socketCloseListener: 0,
217 // Incomplete info games: show move played
219 // Intervals from setInterval():
223 // Related to (killing of) self multi-connects:
228 $route: function(to, from) {
229 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
231 this.cleanBeforeDestroy();
232 else if (from.params["id"] != to.params["id"]) {
233 // Change everything:
234 this.cleanBeforeDestroy();
235 let boardDiv = document.querySelector(".game");
237 // In case of incomplete information variant:
238 boardDiv.style.visibility = "hidden";
242 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
245 // NOTE: some redundant code with Hall.vue (mostly related to people array)
246 created: function() {
249 mounted: function() {
250 document.getElementById("chatWrap")
251 .addEventListener("click", (e) => {
252 processModalClick(e, () => {
253 this.toggleChat("close")
256 ["rematchDiv", "scoreDiv"].forEach(
258 document.getElementById(eltName)
259 .addEventListener("click", processModalClick);
262 if ("ontouchstart" in window) {
263 // Disable tooltips on smartphones:
264 document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => {
265 elt.classList.remove("tooltip");
269 beforeDestroy: function() {
270 this.cleanBeforeDestroy();
273 cleanBeforeDestroy: function() {
274 clearInterval(this.socketCloseListener);
275 document.removeEventListener('visibilitychange', this.visibilityChange);
276 window.removeEventListener('focus', this.onFocus);
277 window.removeEventListener('blur', this.onBlur);
278 if (!!this.askLastate) clearInterval(this.askLastate);
279 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
280 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
281 this.conn.removeEventListener("message", this.socketMessageListener);
282 this.send("disconnect");
285 visibilityChange: function() {
286 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
287 this.focus = (document.visibilityState == "visible");
288 if (!this.focus && !!this.rematchOffer) {
289 this.rematchOffer = "";
290 this.send("rematchoffer", { data: false });
291 // Do not remove rematch offer from (local) storage
293 this.send(this.focus ? "getfocus" : "losefocus");
295 onFocus: function() {
297 this.send("getfocus");
301 if (!!this.rematchOffer) {
302 this.rematchOffer = "";
303 this.send("rematchoffer", { data: false });
305 this.send("losefocus");
307 isLargeScreen: function() {
308 return window.innerWidth >= 500;
310 participateInChat: function(p) {
311 return Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus) && !!p.name;
313 someAnonymousPresent: function() {
315 Object.values(this.people).some(p =>
316 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
320 atCreation: function() {
321 document.addEventListener('visibilitychange', this.visibilityChange);
322 window.addEventListener('focus', this.onFocus);
323 window.addEventListener('blur', this.onBlur);
324 // 0] (Re)Set variables
325 this.gameRef = this.$route.params["id"];
326 // next = next corr games IDs to navigate faster (if applicable)
327 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
328 // Always add myself to players' list
329 const my = this.st.user;
330 const tmpId = getRandString();
338 tmpId: { focus: true }
343 players: [{ name: "" }, { name: "" }],
347 let chatComp = this.$refs["chatcomp"];
348 if (!!chatComp) chatComp.chats = [];
349 this.virtualClocks = [[0,0], [0,0]];
352 this.lastateAsked = false;
353 this.rematchOffer = "";
354 this.lastate = undefined;
355 this.roomInitialized = false;
356 this.askGameTime = 0;
357 this.gameIsLoading = false;
358 this.gotLastate = false;
359 this.gotMoveIdx = -1;
360 this.opponentGotMove = false;
361 this.askLastate = null;
362 this.retrySendmove = null;
363 this.clockUpdate = null;
364 this.newConnect = {};
365 // 1] Initialize connection
366 this.connexionString =
368 "/?sid=" + this.st.user.sid +
369 "&id=" + this.st.user.id +
372 // Discard potential "/?next=[...]" for page indication:
373 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
374 this.conn = new WebSocket(this.connexionString);
375 this.conn.addEventListener("message", this.socketMessageListener);
376 this.socketCloseListener = setInterval(
378 if (this.conn.readyState == 3) {
379 this.conn.removeEventListener(
380 "message", this.socketMessageListener);
381 this.conn = new WebSocket(this.connexionString);
382 this.conn.addEventListener("message", this.socketMessageListener);
387 // Socket init required before loading remote game:
388 const socketInit = callback => {
389 if (this.conn.readyState == 1)
393 // Socket not ready yet (initial loading)
394 // NOTE: first arg is Websocket object, unused here:
395 this.conn.onopen = () => callback();
397 this.fetchGame((game) => {
399 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
401 // Live game stored remotely: need socket to retrieve it
402 // NOTE: the callback "roomInit" will be lost, so it's not provided.
403 // --> It will be given when receiving "fullgame" socket event.
404 socketInit(() => { this.send("askfullgame"); });
407 roomInit: function() {
408 if (!this.roomInitialized) {
409 // Notify the room only now that I connected, because
410 // messages might be lost otherwise (if game loading is slow)
411 this.send("connect");
412 this.send("pollclients");
413 // We may ask fullgame several times if some moves are lost,
414 // but room should be init only once:
415 this.roomInitialized = true;
418 send: function(code, obj) {
419 if (!!this.conn && this.conn.readyState == 1)
420 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
422 isConnected: function(index) {
423 const player = this.game.players[index];
424 // Is it me ? In this case no need to bother with focus
425 if (this.st.user.sid == player.sid || this.st.user.id == player.id)
426 // Still have to check for name (because of potential multi-accounts
427 // on same browser, although this should be rare...)
428 return (!this.st.user.name || this.st.user.name == player.name);
429 // Try to find a match in people:
433 Object.keys(this.people).some(sid => {
436 Object.values(this.people[sid].tmpIds).some(v => v.focus)
443 Object.values(this.people).some(p => {
446 Object.values(p.tmpIds).some(v => v.focus)
452 getOppsid: function() {
453 let oppsid = this.game.oppsid;
455 oppsid = Object.keys(this.people).find(
456 sid => this.people[sid].id == this.game.oppid
459 // oppsid is useful only if opponent is online:
460 if (!!oppsid && !!this.people[oppsid]) return oppsid;
463 // NOTE: action if provided is always a closing action
464 toggleChat: function(action) {
465 if (!action && document.getElementById("modalChat").checked)
467 document.getElementById("inputChat").focus();
469 document.getElementById("chatBtn").classList.remove("somethingnew");
470 if (!!this.game.mycolor) {
471 // Update "chatRead" variable either on server or locally
472 if (this.game.type == "corr")
473 this.updateCorrGame({ chatRead: this.game.mycolor });
474 else if (this.game.type == "live")
475 GameStorage.update(this.gameRef, { chatRead: true });
479 processChat: function(chat) {
480 this.send("newchat", { data: chat });
481 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
482 if (!!this.game.mycolor) {
483 if (this.game.type == "corr")
484 this.updateCorrGame({ chat: chat });
487 chat.added = Date.now();
488 GameStorage.update(this.gameRef, { chat: chat });
492 clearChat: function() {
493 if (!!this.game.mycolor) {
494 if (this.game.type == "corr") {
498 { data: { gid: this.game.id } }
502 GameStorage.update(this.gameRef, { delchat: true });
504 this.$set(this.game, "chats", []);
507 getGameType: function(game) {
508 if (!!game.id.toString().match(/^i/)) return "import";
509 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
511 // Notify something after a new move (to opponent and me on MyGames page)
512 notifyMyGames: function(thing, data) {
517 targets: this.game.players.map(p => {
518 return { sid: p.sid, id: p.id };
523 showNextGame: function() {
524 // Did I play in current game? If not, add it to nextIds list
525 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
526 this.nextIds.unshift(this.game.id);
527 const nextGid = this.nextIds.pop();
529 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
531 askGameAgain: function() {
532 this.gameIsLoading = true;
533 const currentUrl = document.location.href;
534 const doAskGame = () => {
535 if (document.location.href != currentUrl) return; //page change
536 this.fetchGame((game) => {
538 // This is my game: just reload.
541 // Just ask fullgame again (once!), this is much simpler.
542 // If this fails, the user could just reload page :/
543 this.send("askfullgame");
546 // Delay of at least 2s between two game requests
547 const now = Date.now();
548 const delay = Math.max(2000 - (now - this.askGameTime), 0);
549 this.askGameTime = now;
550 setTimeout(doAskGame, delay);
552 socketMessageListener: function(msg) {
553 if (!this.conn) return;
554 const data = JSON.parse(msg.data);
557 // TODO: shuffling and random filtering on server,
558 // if the room is really crowded.
559 Object.keys(data.sockIds).forEach(sid => {
560 if (sid != this.st.user.sid) {
561 this.send("askidentity", { target: sid });
562 this.people[sid] = { tmpIds: data.sockIds[sid] };
565 // Complete my tmpIds:
566 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
571 if (!this.people[data.from[0]]) {
572 // focus depends on the tmpId (e.g. tab)
578 [data.from[1]]: { focus: true }
582 // For self multi-connects tests:
583 this.newConnect[data.from[0]] = true;
584 this.send("askidentity", { target: data.from[0] });
586 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
587 this.$forceUpdate(); //TODO: shouldn't be required
591 if (!this.people[data.from[0]]) return;
592 delete this.people[data.from[0]].tmpIds[data.from[1]];
593 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
594 this.$delete(this.people, data.from[0]);
595 else this.$forceUpdate(); //TODO: shouldn't be required
598 let player = this.people[data.from[0]];
600 player.tmpIds[data.from[1]].focus = true;
601 this.$forceUpdate(); //TODO: shouldn't be required
606 let player = this.people[data.from[0]];
608 player.tmpIds[data.from[1]].focus = false;
609 this.$forceUpdate(); //TODO: shouldn't be required
613 case "askidentity": {
614 // Request for identification
616 // Decompose to avoid revealing email
617 name: this.st.user.name,
618 sid: this.st.user.sid,
621 this.send("identity", { data: me, target: data.from });
625 const user = data.data;
626 let player = this.people[user.sid];
627 // player.tmpIds is already set
628 player.name = user.name;
630 if (this.game.type == "live") {
632 this.game.players.findIndex(p => p.sid == this.st.user.sid);
633 // Sometimes a player name isn't stored yet (TODO: why?)
636 !this.game.players[1 - myGidx].name &&
637 this.game.players[1 - myGidx].sid == user.sid &&
640 this.game.players[1-myGidx].name = user.name;
643 { playerName: { idx: 1 - myGidx, name: user.name } }
647 this.$forceUpdate(); //TODO: shouldn't be required
648 // If I multi-connect, kill current connexion if no mark (I'm older)
649 if (this.newConnect[user.sid]) {
650 delete this.newConnect[user.sid];
653 user.id == this.st.user.id &&
654 user.sid != this.st.user.sid
656 this.cleanBeforeDestroy();
657 alert(this.st.tr["New connexion detected: tab now offline"]);
661 // Ask potentially missed last state, if opponent and I play
664 !!this.game.mycolor &&
665 this.game.type == "live" &&
666 this.game.score == "*" &&
667 this.game.players.some(p => p.sid == user.sid)
669 this.send("asklastate", { target: user.sid });
671 this.askLastate = setInterval(
673 // Ask at most 3 times:
674 // if no reply after that there should be a network issue.
678 !!this.people[user.sid]
680 this.send("asklastate", { target: user.sid });
683 clearInterval(this.askLastate);
692 // Send current (live or import) game,
693 // if not asked by any of the players
695 this.game.type != "corr" &&
696 this.game.players.every(p => p.sid != data.from[0])
700 // FEN is current position, unused for now
702 players: this.game.players,
704 cadence: this.game.cadence,
705 score: this.game.score
707 this.send("game", { data: myGame, target: data.from });
711 const gameToSend = Object.keys(this.game)
714 "id","fen","players","vid","cadence","fenStart","vname",
715 "moves","clocks","score","drawOffer","rematchOffer"
719 obj[k] = this.game[k];
724 this.send("fullgame", { data: gameToSend, target: data.from });
727 if (!!data.data.empty) {
728 alert(this.st.tr["The game should be in another tab"]);
732 // Callback "roomInit" to poll clients only after game is loaded
733 this.loadVariantThenGame(data.data, this.roomInit);
736 // Sending informative last state if I played a move or score != "*"
737 // If the game or moves aren't loaded yet, delay the sending:
738 // TODO: socket init after game load, so the game is supposedly ready
739 if (!this.game || !this.game.moves) this.lastateAsked = true;
740 else this.sendLastate(data.from);
743 // Got opponent infos about last move
744 this.gotLastate = true;
745 this.lastate = data.data;
746 if (this.game.rendered)
747 // Game is rendered (Board component)
748 this.processLastate();
749 // Else: will be processed when game is ready
753 const movePlus = data.data;
754 const movesCount = this.game.moves.length;
755 if (movePlus.index > movesCount) {
756 // This can only happen if I'm an observer and missed a move.
757 if (this.gotMoveIdx < movePlus.index)
758 this.gotMoveIdx = movePlus.index;
759 if (!this.gameIsLoading) this.askGameAgain();
763 movePlus.index < movesCount ||
764 this.gotMoveIdx >= movePlus.index
766 // Opponent re-send but we already have the move:
767 // (maybe he didn't receive our pingback...)
768 this.send("gotmove", {data: movePlus.index, target: data.from});
770 this.gotMoveIdx = movePlus.index;
771 const receiveMyMove = (movePlus.color == this.game.mycolor);
772 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
773 if (!receiveMyMove && !!this.game.mycolor) {
774 // Notify opponent that I got the move:
777 { data: movePlus.index, target: data.from }
779 // And myself if I'm elsewhere:
785 (this.game.players[moveColIdx].name || "@nonymous") +
791 if (movePlus.cancelDrawOffer) {
792 // Opponent refuses draw
794 // NOTE for corr games: drawOffer reset by player in turn
796 this.game.type == "live" &&
797 !!this.game.mycolor &&
800 GameStorage.update(this.gameRef, { drawOffer: "" });
803 this.$refs["basegame"].play(
804 movePlus.move, "received", null, true);
805 this.game.clocks[moveColIdx] = movePlus.clock;
808 { receiveMyMove: receiveMyMove }
815 this.opponentGotMove = true;
816 // Now his clock starts running on my side:
817 const oppIdx = ['w','b'].indexOf(this.vr.turn);
818 // NOTE: next line to avoid multi-resetClocks when several tabs
819 // on same game, resulting in a faster countdown.
820 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
825 const score = (data.data == "b" ? "1-0" : "0-1");
826 const side = (data.data == "w" ? "White" : "Black");
827 this.gameOver(score, side + " surrender");
830 this.gameOver("?", "Stop");
833 this.gameOver("1/2", data.data);
836 // NOTE: observers don't know who offered draw
837 this.drawOffer = "received";
838 if (!!this.game.mycolor && this.game.type == "live") {
841 { drawOffer: V.GetOppCol(this.game.mycolor) }
846 // NOTE: observers don't know who offered rematch
847 this.rematchOffer = data.data ? "received" : "";
848 if (!!this.game.mycolor && this.game.type == "live") {
851 { rematchOffer: V.GetOppCol(this.game.mycolor) }
856 // A game started, redirect if I'm playing in
857 const gameInfo = data.data;
858 const gameType = this.getGameType(gameInfo);
860 gameType == "live" &&
861 gameInfo.players.some(p => p.sid == this.st.user.sid)
863 this.addAndGotoLiveGame(gameInfo);
865 gameType == "corr" &&
866 gameInfo.players.some(p => p.id == this.st.user.id)
868 this.$router.push("/game/" + gameInfo.id);
870 this.rematchId = gameInfo.id;
871 document.getElementById("modalRematch").checked = true;
876 let chat = data.data;
877 this.$refs["chatcomp"].newChat(chat);
878 if (this.game.type == "live") {
879 chat.added = Date.now();
880 if (!!this.game.mycolor)
881 GameStorage.update(this.gameRef, { chat: chat });
883 if (!document.getElementById("modalChat").checked)
884 document.getElementById("chatBtn").classList.add("somethingnew");
889 updateCorrGame: function(obj, callback) {
899 if (!!callback) callback();
904 sendLastate: function(target) {
905 // Send our "last state" informations to opponent
906 const L = this.game.moves.length;
907 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
910 (L > 0 && this.vr.turn != this.game.mycolor)
911 ? this.game.moves[L - 1]
913 clock: this.game.clocks[myIdx],
914 // Since we played a move (or abort or resign),
915 // only drawOffer=="sent" is possible
916 drawSent: this.drawOffer == "sent",
917 rematchSent: this.rematchOffer == "sent",
918 score: this.game.score != "*" ? this.game.score : undefined,
919 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
922 this.send("lastate", { data: myLastate, target: target });
924 // lastate was received, but maybe game wasn't ready yet:
925 processLastate: function() {
926 const data = this.lastate;
927 this.lastate = undefined; //security...
928 const L = this.game.moves.length;
929 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
930 this.game.clocks[oppIdx] = data.clock;
931 if (data.movesCount > L) {
932 // Just got last move from him
933 this.$refs["basegame"].play(data.lastMove, "received", null, true);
934 this.processMove(data.lastMove);
936 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
939 if (data.drawSent) this.drawOffer = "received";
940 if (data.rematchSent) this.rematchOffer = "received";
943 if (this.game.score == "*")
944 this.gameOver(data.score, data.scoreMsg);
947 clickDraw: function() {
948 if (!this.game.mycolor || this.game.type == "import") return;
949 if (["received", "threerep"].includes(this.drawOffer)) {
950 if (!confirm(this.st.tr["Accept draw?"])) return;
952 this.drawOffer == "received"
954 : "Three repetitions";
955 this.send("draw", { data: message });
956 this.gameOver("1/2", message);
957 } else if (this.drawOffer == "") {
958 // No effect if drawOffer == "sent"
959 if (this.game.mycolor != this.vr.turn) {
960 alert(this.st.tr["Draw offer only in your turn"]);
963 if (!confirm(this.st.tr["Offer draw?"])) return;
964 this.drawOffer = "sent";
965 this.send("drawoffer");
966 if (this.game.type == "live") {
969 { drawOffer: this.game.mycolor }
971 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
974 addAndGotoLiveGame: function(gameInfo, callback) {
975 const game = Object.assign(
979 // (other) Game infos: constant
980 fenStart: gameInfo.fen,
981 vname: this.game.vname,
983 // Game state (including FEN): will be updated
985 clocks: [-1, -1], //-1 = unstarted
989 GameStorage.add(game, (err) => {
990 // No error expected.
992 if (this.st.settings.sound)
993 new Audio("/sounds/newgame.flac").play().catch(() => {});
994 if (!!callback) callback();
995 this.$router.push("/game/" + gameInfo.id);
999 clickRematch: function() {
1000 if (!this.game.mycolor || this.game.type == "import") return;
1001 if (this.rematchOffer == "received") {
1002 // Start a new game!
1004 id: getRandString(), //ignored if corr
1005 fen: V.GenRandInitFen(this.game.randomness),
1006 players: this.game.players.reverse(),
1008 cadence: this.game.cadence
1010 const notifyNewGame = () => {
1011 const oppsid = this.getOppsid(); //may be null
1012 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
1013 // To main Hall if corr game:
1014 if (this.game.type == "corr")
1015 this.send("newgame", { data: gameInfo, page: "/" });
1016 // Also to MyGames page:
1017 this.notifyMyGames("newgame", gameInfo);
1019 if (this.game.type == "live")
1020 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1027 // cid is useful to delete the challenge:
1028 data: { gameInfo: gameInfo },
1029 success: (response) => {
1030 gameInfo.id = response.gameId;
1032 this.$router.push("/game/" + response.gameId);
1037 } else if (this.rematchOffer == "") {
1038 this.rematchOffer = "sent";
1039 this.send("rematchoffer", { data: true });
1040 if (this.game.type == "live") {
1043 { rematchOffer: this.game.mycolor }
1045 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1046 } else if (this.rematchOffer == "sent") {
1047 // Toggle rematch offer (on --> off)
1048 this.rematchOffer = "";
1049 this.send("rematchoffer", { data: false });
1050 if (this.game.type == "live") {
1053 { rematchOffer: '' }
1055 } else this.updateCorrGame({ rematchOffer: 'n' });
1058 abortGame: function() {
1059 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1061 this.gameOver("?", "Stop");
1064 resign: function() {
1065 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1067 this.send("resign", { data: this.game.mycolor });
1068 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1069 const side = (this.game.mycolor == "w" ? "White" : "Black");
1070 this.gameOver(score, side + " surrender");
1072 loadGame: function(game, callback) {
1073 const gtype = game.type || this.getGameType(game);
1074 const tc = extractTime(game.cadence);
1075 const myIdx = game.players.findIndex(p => {
1076 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1078 // Sometimes the name isn't stored yet (TODO: why?)
1082 !game.players[myIdx].name &&
1085 game.players[myIdx].name = this.st.user.name;
1088 { playerName: { idx: myIdx, name: this.st.user.name } }
1091 // "mycolor" is undefined for observers
1092 const mycolor = [undefined, "w", "b"][myIdx + 1];
1093 if (gtype == "corr") {
1094 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1095 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1096 // NOTE: clocks in seconds
1097 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1098 game.clocks = [tc.mainTime, tc.mainTime];
1099 const L = game.moves.length;
1100 if (game.score == "*") {
1103 game.clocks[L % 2] -=
1104 (Date.now() - game.moves[L-1].played) / 1000;
1107 // Now that we used idx and played, re-format moves as for live games
1108 game.moves = game.moves.map(m => m.squares);
1110 else if (gtype == "live") {
1111 if (game.clocks[0] < 0) {
1112 // Game is unstarted. clock is ignored until move 2
1113 game.clocks = [tc.mainTime, tc.mainTime];
1115 // I play in this live game
1118 { clocks: game.clocks }
1123 // It's my turn: clocks not updated yet
1124 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1128 // gtype == "import"
1129 game.clocks = [tc.mainTime, tc.mainTime];
1130 // Live games before 26/03/2020 don't have chat history:
1131 if (!game.chats) game.chats = []; //TODO: remove line
1132 // Sort chat messages from newest to oldest
1133 game.chats.sort((c1, c2) => c2.added - c1.added);
1136 game.chats.length > 0 &&
1137 (!game.chatRead || game.chatRead < game.chats[0].added)
1139 // A chat message arrived since my last reading:
1140 document.getElementById("chatBtn").classList.add("somethingnew");
1142 // TODO: merge next 2 "if" conditions
1143 if (!!game.drawOffer) {
1144 if (game.drawOffer == "t")
1145 // Three repetitions
1146 this.drawOffer = "threerep";
1148 // Draw offered by any of the players:
1149 if (myIdx < 0) this.drawOffer = "received";
1151 // I play in this game:
1153 (game.drawOffer == "w" && myIdx == 0) ||
1154 (game.drawOffer == "b" && myIdx == 1)
1156 this.drawOffer = "sent";
1157 else this.drawOffer = "received";
1161 if (!!game.rematchOffer) {
1162 if (myIdx < 0) this.rematchOffer = "received";
1164 // I play in this game:
1166 (game.rematchOffer == "w" && myIdx == 0) ||
1167 (game.rematchOffer == "b" && myIdx == 1)
1169 this.rematchOffer = "sent";
1170 else this.rematchOffer = "received";
1173 this.repeat = {}; //reset: scan past moves' FEN:
1175 this.vr = new V(game.fenStart);
1177 game.moves.forEach(m => {
1178 playMove(m, this.vr);
1179 const fenIdx = this.vr.getFenForRepeat();
1180 this.repeat[fenIdx] = this.repeat[fenIdx]
1181 ? this.repeat[fenIdx] + 1
1184 // Imported games don't have current FEN
1185 if (!game.fen) game.fen = this.vr.getFen();
1186 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1187 this.game = Object.assign(
1188 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1191 increment: tc.increment,
1193 // opponent sid not strictly required (or available), but easier
1194 // at least oppsid or oppid is available anyway:
1195 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1196 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1200 this.$refs["basegame"].re_setVariables(this.game);
1201 if (!this.gameIsLoading) {
1203 this.gotMoveIdx = game.moves.length - 1;
1204 // If we arrive here after 'nextGame' action, the board might be hidden
1205 let boardDiv = document.querySelector(".game");
1206 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1207 boardDiv.style.visibility = "visible";
1209 this.re_setClocks();
1210 this.$nextTick(() => {
1211 this.game.rendered = true;
1212 // Did lastate arrive before game was rendered?
1213 if (this.lastate) this.processLastate();
1215 if (this.lastateAsked) {
1216 this.lastateAsked = false;
1217 this.sendLastate(game.oppsid);
1219 if (this.gameIsLoading) {
1220 this.gameIsLoading = false;
1221 if (this.gotMoveIdx >= game.moves.length)
1222 // Some moves arrived meanwhile...
1223 this.askGameAgain();
1225 if (!!callback) callback();
1227 loadVariantThenGame: async function(game, callback) {
1228 await import("@/variants/" + game.vname + ".js")
1229 .then((vModule) => {
1230 window.V = vModule[game.vname + "Rules"];
1231 this.loadGame(game, callback);
1234 // 3 cases for loading a game:
1235 // - from indexedDB (running or completed live game I play)
1236 // - from server (one correspondance game I play[ed] or not)
1237 // - from remote peer (one live game I don't play, finished or not)
1238 fetchGame: function(callback) {
1239 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1240 // corr games identifiers are integers
1245 data: { gid: this.gameRef },
1247 res.game.moves.forEach(m => {
1248 m.squares = JSON.parse(m.squares);
1255 else if (!!this.gameRef.match(/^i/))
1256 // Game import (maybe remote)
1257 ImportgameStorage.get(this.gameRef, callback);
1259 // Local live game (or remote)
1260 GameStorage.get(this.gameRef, callback);
1262 re_setClocks: function() {
1263 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1264 if (this.game.moves.length < 2 || this.game.score != "*") {
1265 // 1st move not completed yet, or game over: freeze time
1268 const currentTurn = this.vr.turn;
1269 const currentMovesCount = this.game.moves.length;
1270 const colorIdx = ["w", "b"].indexOf(currentTurn);
1271 this.clockUpdate = setInterval(
1274 this.game.clocks[colorIdx] < 0 ||
1275 this.game.moves.length > currentMovesCount ||
1276 this.game.score != "*"
1278 clearInterval(this.clockUpdate);
1279 this.clockUpdate = null;
1280 if (this.game.clocks[colorIdx] < 0)
1282 currentTurn == "w" ? "0-1" : "1-0",
1289 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1296 // Update variables and storage after a move:
1297 processMove: function(move, data) {
1298 if (this.game.type == "import")
1299 // Shouldn't receive any messages in this mode:
1301 if (!data) data = {};
1302 const moveCol = this.vr.turn;
1303 const colorIdx = ["w", "b"].indexOf(moveCol);
1304 const nextIdx = 1 - colorIdx;
1305 const doProcessMove = () => {
1306 const origMovescount = this.game.moves.length;
1307 // The move is (about to be) played: stop clock
1308 clearInterval(this.clockUpdate);
1309 this.clockUpdate = null;
1310 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1311 if (this.drawOffer == "received")
1313 this.drawOffer = "";
1314 if (this.game.type == "live" && origMovescount >= 2) {
1315 this.game.clocks[colorIdx] += this.game.increment;
1316 // For a correct display in casqe of disconnected opponent:
1320 ppt(this.game.clocks[colorIdx]).split(':')
1322 GameStorage.update(this.gameRef, {
1323 // It's not my turn anymore:
1328 // Update current game object:
1329 playMove(move, this.vr);
1331 // Received move, score is computed in BaseGame, but maybe not yet.
1332 // ==> Compute it here, although this is redundant (TODO)
1333 data.score = this.vr.getCurrentScore();
1334 if (data.score != "*") this.gameOver(data.score);
1335 this.game.moves.push(move);
1336 this.game.fen = this.vr.getFen();
1337 if (this.game.type == "corr") {
1338 // In corr games, just reset clock to mainTime:
1339 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1341 // If repetition detected, consider that a draw offer was received:
1342 const fenObj = this.vr.getFenForRepeat();
1343 this.repeat[fenObj] =
1344 !!this.repeat[fenObj]
1345 ? this.repeat[fenObj] + 1
1347 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1348 else if (this.drawOffer == "threerep") this.drawOffer = "";
1349 if (!!this.game.mycolor && !data.receiveMyMove) {
1350 // NOTE: 'var' to see that variable outside this block
1351 var filtered_move = getFilteredMove(move);
1353 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1354 // Notify turn on MyGames page:
1363 // Since corr games are stored at only one location, update should be
1364 // done only by one player for each move:
1366 this.game.type == "live" &&
1367 !!this.game.mycolor &&
1368 moveCol != this.game.mycolor &&
1369 this.game.moves.length >= 2
1371 // Receive a move: update initime
1372 this.game.initime = Date.now();
1373 GameStorage.update(this.gameRef, {
1374 // It's my turn now!
1375 initime: this.game.initime
1379 !!this.game.mycolor &&
1380 !data.receiveMyMove &&
1381 (this.game.type == "live" || moveCol == this.game.mycolor)
1384 switch (this.drawOffer) {
1389 drawCode = this.game.mycolor;
1392 drawCode = V.GetOppCol(this.game.mycolor);
1395 if (this.game.type == "corr") {
1396 // corr: only move, fen and score
1397 this.updateCorrGame({
1400 squares: filtered_move,
1403 // Code "n" for "None" to force reset (otherwise it's ignored)
1404 drawOffer: drawCode || "n"
1408 const updateStorage = () => {
1409 GameStorage.update(this.gameRef, {
1411 move: filtered_move,
1412 moveIdx: origMovescount,
1413 clocks: this.game.clocks,
1417 // The active tab can update storage immediately
1418 if (this.focus) updateStorage();
1419 // Small random delay otherwise
1420 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1423 // Send move ("newmove" event) to people in the room (if our turn)
1424 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1426 move: filtered_move,
1427 index: origMovescount,
1428 // color is required to check if this is my move
1429 // (if several tabs opened)
1431 cancelDrawOffer: this.drawOffer == ""
1433 if (this.game.type == "live")
1434 sendMove["clock"] = this.game.clocks[colorIdx];
1435 // (Live) Clocks will re-start when the opponent pingback arrive
1436 this.opponentGotMove = false;
1437 this.send("newmove", {data: sendMove});
1438 // If the opponent doesn't reply gotmove soon enough, re-send move:
1439 // Do this at most 2 times, because mpore would mean network issues,
1440 // opponent would then be expected to disconnect/reconnect.
1442 const currentUrl = document.location.href;
1443 this.retrySendmove = setInterval(
1447 this.opponentGotMove ||
1448 document.location.href != currentUrl //page change
1450 clearInterval(this.retrySendmove);
1453 const oppsid = this.getOppsid();
1455 // Opponent is disconnected: he'll ask last state
1456 clearInterval(this.retrySendmove);
1458 this.send("newmove", { data: sendMove, target: oppsid });
1466 // Not my move or I'm an observer: just start other player's clock
1467 this.re_setClocks();
1470 this.game.type == "corr" &&
1471 moveCol == this.game.mycolor &&
1474 let boardDiv = document.querySelector(".game");
1475 const afterSetScore = () => {
1477 if (this.st.settings.gotonext && this.nextIds.length > 0)
1478 this.showNextGame();
1480 // The board might have been hidden:
1481 if (boardDiv.style.visibility == "hidden")
1482 boardDiv.style.visibility = "visible";
1483 if (data.score == "*") this.re_setClocks();
1486 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1487 // We may play several moves in a row: in case of, remove listener:
1488 let elClone = el.cloneNode(true);
1489 el.parentNode.replaceChild(elClone, el);
1490 elClone.addEventListener(
1493 document.getElementById("modalConfirm").checked = false;
1494 if (!!data.score && data.score != "*")
1496 this.gameOver(data.score, null, afterSetScore);
1497 else afterSetScore();
1500 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1501 const arMove = (Array.isArray(move) ? move : [move]);
1502 for (let i = 0; i < arMove.length; i++)
1503 V.PlayOnBoard(this.vr.board, arMove[i]);
1504 const position = this.vr.getBaseFen();
1505 for (let i = arMove.length - 1; i >= 0; i--)
1506 V.UndoOnBoard(this.vr.board, arMove[i]);
1507 if (["all","byrow"].includes(V.ShowMoves)) {
1508 this.curDiag = getDiagram({
1510 orientation: V.CanFlip ? this.game.mycolor : "w"
1512 document.querySelector("#confirmDiv > .card").style.width =
1513 boardDiv.offsetWidth + "px";
1515 // Incomplete information: just ask confirmation
1516 // Hide the board, because otherwise it could reveal infos
1517 boardDiv.style.visibility = "hidden";
1518 this.moveNotation = getFullNotation(move);
1520 document.getElementById("modalConfirm").checked = true;
1524 if (!!data.score && data.score != "*")
1525 this.gameOver(data.score, null, doProcessMove);
1526 else doProcessMove();
1529 cancelMove: function() {
1530 let boardDiv = document.querySelector(".game");
1531 if (boardDiv.style.visibility == "hidden")
1532 boardDiv.style.visibility = "visible";
1533 document.getElementById("modalConfirm").checked = false;
1534 this.$refs["basegame"].cancelLastMove();
1536 // In corr games, callback to change page only after score is set:
1537 gameOver: function(score, scoreMsg, callback) {
1538 this.game.score = score;
1539 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1540 this.game.scoreMsg = scoreMsg;
1541 // Display result in a un-missable way:
1542 document.getElementById("modalScore").checked = true;
1543 this.$set(this.game, "scoreMsg", scoreMsg);
1544 const myIdx = this.game.players.findIndex(p => {
1545 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1548 // OK, I play in this game
1553 if (this.game.type == "live") {
1554 GameStorage.update(this.gameRef, scoreObj);
1555 // Notify myself locally if I'm elsewhere:
1559 { body: score + " : " + scoreMsg }
1562 if (!!callback) callback();
1564 else this.updateCorrGame(scoreObj, callback);
1565 // Notify the score to main Hall.
1566 // TODO: only one player (currently double send)
1567 this.send("result", { gid: this.game.id, score: score });
1568 // Also to MyGames page (TODO: doubled as well...)
1577 else if (!!callback) callback();
1583 <style lang="sass" scoped>
1584 #scoreDiv > .card, #rematchDiv > .card
1594 background-color: lightgreen
1606 @media screen and (min-width: 768px)
1609 @media screen and (max-width: 767px)
1614 display: inline-block
1618 display: inline-block
1620 display: inline-flex
1624 @media screen and (max-width: 767px)
1627 @media screen and (max-width: 767px)
1630 @media screen and (min-width: 768px)
1642 background-color: #edda99
1644 display: inline-block
1653 display: inline-block
1666 animation: blink-animation 2s steps(3, start) infinite
1667 @keyframes blink-animation
1672 display: inline-block
1684 .draw-sent, .draw-sent:hover
1685 background-color: lightyellow
1687 .draw-received, .draw-received:hover
1688 background-color: lightgreen
1690 .draw-threerep, .draw-threerep:hover
1691 background-color: #e4d1fc
1693 .rematch-sent, .rematch-sent:hover
1694 background-color: lightyellow
1696 .rematch-received, .rematch-received:hover
1697 background-color: lightgreen
1700 background-color: #c5fefe
1713 background-color: lightgreen
1715 background-color: red