3 input#modalInfo.modal(type="checkbox")
6 data-checkbox="modalInfo"
9 label.modal-close(for="modalInfo")
10 p(v-html="infoMessage")
11 input#modalChat.modal(
13 @click="resetChatColor()"
17 data-checkbox="modalChat"
20 label.modal-close(for="modalChat")
22 span {{ st.tr["Participant(s):"] }}
24 v-for="p in Object.values(people)"
25 v-if="p.focus && !!p.name"
29 v-if="Object.values(people).some(p => p.focus && !p.name)"
34 :players="game.players"
35 :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")
92 v-else-if="!!game.mycolor"
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";
154 // rid = remote (socket) ID
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 onMygames: [], //opponents (or me) on "MyGames" page
169 lastate: undefined, //used if opponent send lastate before game is ready
170 repeat: {}, //detect position repetition
171 curDiag: "", //for corr moves confirmation
174 roomInitialized: false,
175 // If newmove has wrong index: ask fullgame again:
177 gameIsLoading: false,
178 // If asklastate got no reply, ask again:
180 gotMoveIdx: -1, //last move index received
181 // If newmove got no pingback, send again:
182 opponentGotMove: false,
184 // Incomplete info games: show move played
186 // Intervals from setInterval():
190 // Related to (killing of) self multi-connects:
196 $route: function(to, from) {
197 if (from.params["id"] != to.params["id"]) {
198 // Change everything:
199 this.cleanBeforeDestroy();
200 let boardDiv = document.querySelector(".game");
202 // In case of incomplete information variant:
203 boardDiv.style.visibility = "hidden";
207 this.gameRef.id = to.params["id"];
208 this.gameRef.rid = to.query["rid"];
209 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
214 // NOTE: some redundant code with Hall.vue (mostly related to people array)
215 created: function() {
218 mounted: function() {
219 document.addEventListener('visibilitychange', this.visibilityChange);
221 .getElementById("chatWrap")
222 .addEventListener("click", processModalClick);
223 if ("ontouchstart" in window) {
224 // Disable tooltips on smartphones:
225 document.getElementsByClassName("tooltip").forEach(elt => {
226 elt.classList.remove("tooltip");
230 beforeDestroy: function() {
231 document.removeEventListener('visibilitychange', this.visibilityChange);
232 this.cleanBeforeDestroy();
235 visibilityChange: function() {
236 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
238 document.visibilityState == "visible"
243 atCreation: function() {
244 // 0] (Re)Set variables
245 this.gameRef.id = this.$route.params["id"];
246 // rid = remote ID to find an observed live game,
247 // next = next corr games IDs to navigate faster
248 // (Both might be undefined)
249 this.gameRef.rid = this.$route.query["rid"];
250 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
251 // Always add myself to players' list
252 const my = this.st.user;
263 players: [{ name: "" }, { name: "" }],
267 let chatComp = this.$refs["chatcomp"];
268 if (!!chatComp) chatComp.chats = [];
269 this.virtualClocks = [[0,0], [0,0]];
272 this.lastateAsked = false;
273 this.rematchOffer = "";
275 this.lastate = undefined;
277 this.roomInitialized = false;
278 this.askGameTime = 0;
279 this.gameIsLoading = false;
280 this.gotLastate = false;
281 this.gotMoveIdx = -1;
282 this.opponentGotMove = false;
283 this.askLastate = null;
284 this.retrySendmove = null;
285 this.clockUpdate = null;
286 this.newConnect = {};
288 // 1] Initialize connection
289 this.connexionString =
296 // Discard potential "/?next=[...]" for page indication:
297 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
298 this.conn = new WebSocket(this.connexionString);
299 this.conn.onmessage = this.socketMessageListener;
300 this.conn.onclose = this.socketCloseListener;
301 // Socket init required before loading remote game:
302 const socketInit = callback => {
303 if (!!this.conn && this.conn.readyState == 1)
307 // Socket not ready yet (initial loading)
308 // NOTE: it's important to call callback without arguments,
309 // otherwise first arg is Websocket object and loadGame fails.
310 this.conn.onopen = () => callback();
312 if (!this.gameRef.rid)
313 // Game stored locally or on server
314 this.loadGame(null, () => socketInit(this.roomInit));
316 // Game stored remotely: need socket to retrieve it
317 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
318 // --> It will be given when receiving "fullgame" socket event.
319 socketInit(this.loadGame);
321 cleanBeforeDestroy: function() {
322 if (!!this.askLastate)
323 clearInterval(this.askLastate);
324 if (!!this.retrySendmove)
325 clearInterval(this.retrySendmove);
326 if (!!this.clockUpdate)
327 clearInterval(this.clockUpdate);
328 this.send("disconnect");
330 roomInit: function() {
331 if (!this.roomInitialized) {
332 // Notify the room only now that I connected, because
333 // messages might be lost otherwise (if game loading is slow)
334 this.send("connect");
335 this.send("pollclients");
336 // We may ask fullgame several times if some moves are lost,
337 // but room should be init only once:
338 this.roomInitialized = true;
341 send: function(code, obj) {
343 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
345 isConnected: function(index) {
346 const player = this.game.players[index];
347 // Is it me ? In this case no need to bother with focus
348 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
349 // Still have to check for name (because of potential multi-accounts
350 // on same browser, although this should be rare...)
351 return (!this.st.user.name || this.st.user.name == player.name);
352 // Try to find a match in people:
356 Object.keys(this.people).some(sid =>
357 sid == player.sid && this.people[sid].focus)
362 Object.values(this.people).some(p =>
363 p.id == player.uid && p.focus)
367 getOppsid: function() {
368 let oppsid = this.game.oppsid;
370 oppsid = Object.keys(this.people).find(
371 sid => this.people[sid].id == this.game.oppid
374 // oppsid is useful only if opponent is online:
375 if (!!oppsid && !!this.people[oppsid]) return oppsid;
378 resetChatColor: function() {
379 // TODO: this is called twice, once on opening an once on closing
380 document.getElementById("chatBtn").classList.remove("somethingnew");
382 processChat: function(chat) {
383 this.send("newchat", { data: chat });
384 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
385 if (this.game.type == "corr" && this.st.user.id > 0)
386 this.updateCorrGame({ chat: chat });
388 clearChat: function() {
389 // Nothing more to do if game is live (chats not recorded)
390 if (this.game.type == "corr") {
391 if (!!this.game.mycolor) {
395 { data: { gid: this.game.id } }
398 this.$set(this.game, "chats", []);
401 getGameType: function(game) {
402 return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
404 // Notify turn after a new move (to opponent and me on MyGames page)
405 notifyTurn: function(sid) {
406 const player = this.people[sid];
407 const colorIdx = this.game.players.findIndex(
408 p => p.sid == sid || p.uid == player.id);
409 const color = ["w","b"][colorIdx];
410 const movesCount = this.game.moves.length;
412 (color == "w" && movesCount % 2 == 0) ||
413 (color == "b" && movesCount % 2 == 1);
414 this.send("turnchange", { target: sid, yourTurn: yourTurn });
416 showNextGame: function() {
417 // Did I play in current game? If not, add it to nextIds list
418 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
419 this.nextIds.unshift(this.game.id);
420 const nextGid = this.nextIds.pop();
422 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
424 askGameAgain: function() {
425 this.gameIsLoading = true;
426 const currentUrl = document.location.href;
427 const doAskGame = () => {
428 if (document.location.href != currentUrl) return; //page change
429 if (!this.gameRef.rid)
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", { target: this.gameRef.rid });
437 // Delay of at least 2s between two game requests
438 const now = Date.now();
439 const delay = Math.max(2000 - (now - this.askGameTime), 0);
440 this.askGameTime = now;
441 setTimeout(doAskGame, delay);
443 socketMessageListener: function(msg) {
444 if (!this.conn) return;
445 const data = JSON.parse(msg.data);
448 data.sockIds.forEach(sid => {
449 if (sid != this.st.user.sid) {
450 this.people[sid] = { focus: true };
451 this.send("askidentity", { target: sid });
456 if (!this.people[data.from]) {
457 this.people[data.from] = { focus: true };
458 this.newConnect[data.from] = true; //for self multi-connects tests
459 this.send("askidentity", { target: data.from });
463 this.$delete(this.people, data.from);
466 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
467 // Either me (another tab) or opponent
468 const sid = data.from;
469 if (!this.onMygames.some(s => s == sid))
471 this.onMygames.push(sid);
472 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
475 if (!this.people[sid])
476 this.send("askidentity", { target: sid });
479 ArrayFun.remove(this.onMygames, sid => sid == data.from);
482 let player = this.people[data.from];
485 this.$forceUpdate(); //TODO: shouldn't be required
490 let player = this.people[data.from];
492 player.focus = false;
493 this.$forceUpdate(); //TODO: shouldn't be required
498 // I logged in elsewhere:
500 alert(this.st.tr["New connexion detected: tab now offline"]);
502 case "askidentity": {
503 // Request for identification
505 // Decompose to avoid revealing email
506 name: this.st.user.name,
507 sid: this.st.user.sid,
510 this.send("identity", { data: me, target: data.from });
514 const user = data.data;
515 let player = this.people[user.sid];
516 // player.focus is already set
517 player.name = user.name;
519 this.$forceUpdate(); //TODO: shouldn't be required
520 // If I multi-connect, kill current connexion if no mark (I'm older)
521 if (this.newConnect[user.sid]) {
524 user.id == this.st.user.id &&
525 user.sid != this.st.user.sid &&
526 !this.killed[this.st.user.sid]
528 this.send("killme", { sid: this.st.user.sid });
529 this.killed[this.st.user.sid] = true;
531 delete this.newConnect[user.sid];
533 if (!this.killed[this.st.user.sid]) {
534 // Ask potentially missed last state, if opponent and I play
536 !!this.game.mycolor &&
537 this.game.type == "live" &&
538 this.game.score == "*" &&
539 this.game.players.some(p => p.sid == user.sid)
541 this.send("asklastate", { target: user.sid });
543 this.askLastate = setInterval(
545 // Ask at most 3 times:
546 // if no reply after that there should be a network issue.
550 !!this.people[user.sid]
552 this.send("asklastate", { target: user.sid });
555 clearInterval(this.askLastate);
565 // Send current (live) game if not asked by any of the players
567 this.game.type == "live" &&
568 this.game.players.every(p => p.sid != data.from[0])
573 players: this.game.players,
575 cadence: this.game.cadence,
576 score: this.game.score,
577 rid: this.st.user.sid //useful in Hall if I'm an observer
579 this.send("game", { data: myGame, target: data.from });
583 const gameToSend = Object.keys(this.game)
586 "id","fen","players","vid","cadence","fenStart","vname",
587 "moves","clocks","initime","score","drawOffer","rematchOffer"
591 obj[k] = this.game[k];
596 this.send("fullgame", { data: gameToSend, target: data.from });
599 // Callback "roomInit" to poll clients only after game is loaded
600 this.loadGame(data.data, this.roomInit);
603 // Sending informative last state if I played a move or score != "*"
604 // If the game or moves aren't loaded yet, delay the sending:
605 if (!this.game || !this.game.moves) this.lastateAsked = true;
606 else this.sendLastate(data.from);
609 // Got opponent infos about last move
610 this.gotLastate = true;
611 if (!data.data.nothing) {
612 this.lastate = data.data;
613 if (this.game.rendered)
614 // Game is rendered (Board component)
615 this.processLastate();
616 // Else: will be processed when game is ready
621 const movePlus = data.data;
622 const movesCount = this.game.moves.length;
623 if (movePlus.index > movesCount) {
624 // This can only happen if I'm an observer and missed a move.
625 if (this.gotMoveIdx < movePlus.index)
626 this.gotMoveIdx = movePlus.index;
627 if (!this.gameIsLoading) this.askGameAgain();
631 movePlus.index < movesCount ||
632 this.gotMoveIdx >= movePlus.index
634 // Opponent re-send but we already have the move:
635 // (maybe he didn't receive our pingback...)
636 this.send("gotmove", {data: movePlus.index, target: data.from});
638 this.gotMoveIdx = movePlus.index;
639 const receiveMyMove = (movePlus.color == this.game.mycolor);
640 if (!receiveMyMove && !!this.game.mycolor)
641 // Notify opponent that I got the move:
642 this.send("gotmove", {data: movePlus.index, target: data.from});
643 if (movePlus.cancelDrawOffer) {
644 // Opponent refuses draw
646 // NOTE for corr games: drawOffer reset by player in turn
648 this.game.type == "live" &&
649 !!this.game.mycolor &&
652 GameStorage.update(this.gameRef.id, { drawOffer: "" });
655 this.$refs["basegame"].play(movePlus.move, "received", null, true);
659 clock: movePlus.clock,
660 receiveMyMove: receiveMyMove
668 this.opponentGotMove = true;
669 // Now his clock starts running:
670 const oppIdx = ['w','b'].indexOf(this.vr.turn);
671 this.game.initime[oppIdx] = Date.now();
676 const score = data.side == "b" ? "1-0" : "0-1";
677 const side = data.side == "w" ? "White" : "Black";
678 this.gameOver(score, side + " surrender");
681 this.gameOver("?", "Stop");
684 this.gameOver("1/2", data.data);
687 // NOTE: observers don't know who offered draw
688 this.drawOffer = "received";
691 // NOTE: observers don't know who offered rematch
692 this.rematchOffer = data.data ? "received" : "";
695 // A game started, redirect if I'm playing in
696 const gameInfo = data.data;
697 const gameType = this.getGameType(gameInfo);
699 gameType == "live" &&
700 gameInfo.players.some(p => p.sid == this.st.user.sid)
702 this.addAndGotoLiveGame(gameInfo);
704 gameType == "corr" &&
705 gameInfo.players.some(p => p.uid == this.st.user.id)
707 this.$router.push("/game/" + gameInfo.id);
710 if (gameInfo.cadence.indexOf('d') === -1) {
712 // Select sid of any of the online players:
714 gameInfo.players.forEach(p => {
715 if (!!this.people[p.sid]) onlineSid.push(p.sid);
717 urlRid += onlineSid[Math.floor(Math.random() * onlineSid.length)];
720 this.st.tr["Rematch in progress:"] +
721 " <a href='#/game/" +
722 gameInfo.id + urlRid +
725 gameInfo.id + urlRid +
727 document.getElementById("modalInfo").checked = true;
732 this.newChat = data.data;
733 if (!document.getElementById("modalChat").checked)
734 document.getElementById("chatBtn").classList.add("somethingnew");
738 socketCloseListener: function() {
739 this.conn = new WebSocket(this.connexionString);
740 this.conn.addEventListener("message", this.socketMessageListener);
741 this.conn.addEventListener("close", this.socketCloseListener);
743 updateCorrGame: function(obj, callback) {
749 gid: this.gameRef.id,
753 if (!!callback) callback();
758 sendLastate: function(target) {
760 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
761 this.game.score != "*" ||
762 this.drawOffer == "sent" ||
763 this.rematchOffer == "sent"
765 // Send our "last state" informations to opponent
766 const L = this.game.moves.length;
767 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
769 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
770 clock: this.game.clocks[myIdx],
771 // Since we played a move (or abort or resign),
772 // only drawOffer=="sent" is possible
773 drawSent: this.drawOffer == "sent",
774 rematchSent: this.rematchOffer == "sent",
775 score: this.game.score,
776 score: this.game.scoreMsg,
778 initime: this.game.initime[1 - myIdx] //relevant only if I played
780 this.send("lastate", { data: myLastate, target: target });
782 this.send("lastate", { data: {nothing: true}, target: target });
785 // lastate was received, but maybe game wasn't ready yet:
786 processLastate: function() {
787 const data = this.lastate;
788 this.lastate = undefined; //security...
789 const L = this.game.moves.length;
790 if (data.movesCount > L) {
791 // Just got last move from him
792 this.$refs["basegame"].play(data.lastMove, "received", null, true);
793 this.processMove(data.lastMove, { clock: data.clock });
795 if (data.drawSent) this.drawOffer = "received";
796 if (data.rematchSent) this.rematchOffer = "received";
797 if (data.score != "*") {
799 if (this.game.score == "*")
800 this.gameOver(data.score, data.scoreMsg);
803 clickDraw: function() {
804 if (!this.game.mycolor) return; //I'm just spectator
805 if (["received", "threerep"].includes(this.drawOffer)) {
806 if (!confirm(this.st.tr["Accept draw?"])) return;
808 this.drawOffer == "received"
810 : "Three repetitions";
811 this.send("draw", { data: message });
812 this.gameOver("1/2", message);
813 } else if (this.drawOffer == "") {
814 // No effect if drawOffer == "sent"
815 if (this.game.mycolor != this.vr.turn) {
816 alert(this.st.tr["Draw offer only in your turn"]);
819 if (!confirm(this.st.tr["Offer draw?"])) return;
820 this.drawOffer = "sent";
821 this.send("drawoffer");
822 if (this.game.type == "live") {
825 { drawOffer: this.game.mycolor }
827 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
830 addAndGotoLiveGame: function(gameInfo, callback) {
831 const game = Object.assign(
835 // (other) Game infos: constant
836 fenStart: gameInfo.fen,
837 vname: this.game.vname,
839 // Game state (including FEN): will be updated
841 clocks: [-1, -1], //-1 = unstarted
842 initime: [0, 0], //initialized later
846 GameStorage.add(game, (err) => {
847 // No error expected.
849 if (this.st.settings.sound)
850 new Audio("/sounds/newgame.flac").play().catch(() => {});
852 this.$router.push("/game/" + gameInfo.id);
856 clickRematch: function() {
857 if (!this.game.mycolor) return; //I'm just spectator
858 if (this.rematchOffer == "received") {
861 id: getRandString(), //ignored if corr
862 fen: V.GenRandInitFen(this.game.randomness),
863 players: this.game.players.reverse(),
865 cadence: this.game.cadence
867 const notifyNewGame = () => {
868 let oppsid = this.getOppsid(); //may be null
869 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
871 if (this.game.type == "live")
872 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
879 // cid is useful to delete the challenge:
880 data: { gameInfo: gameInfo },
881 success: (response) => {
882 gameInfo.id = response.gameId;
884 this.$router.push("/game/" + response.gameId);
889 } else if (this.rematchOffer == "") {
890 this.rematchOffer = "sent";
891 this.send("rematchoffer", { data: true });
892 if (this.game.type == "live") {
895 { rematchOffer: this.game.mycolor }
897 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
898 } else if (this.rematchOffer == "sent") {
899 // Toggle rematch offer (on --> off)
900 this.rematchOffer = "";
901 this.send("rematchoffer", { data: false });
902 if (this.game.type == "live") {
907 } else this.updateCorrGame({ rematchOffer: 'n' });
910 abortGame: function() {
911 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
912 this.gameOver("?", "Stop");
916 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
918 this.send("resign", { data: this.game.mycolor });
919 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
920 const side = this.game.mycolor == "w" ? "White" : "Black";
921 this.gameOver(score, side + " surrender");
923 // 3 cases for loading a game:
924 // - from indexedDB (running or completed live game I play)
925 // - from server (one correspondance game I play[ed] or not)
926 // - from remote peer (one live game I don't play, finished or not)
927 loadGame: function(game, callback) {
928 const afterRetrieval = async (game) => {
929 const vModule = await import("@/variants/" + game.vname + ".js");
930 window.V = vModule.VariantRules;
931 this.vr = new V(game.fen);
932 const gtype = this.getGameType(game);
933 const tc = extractTime(game.cadence);
934 const myIdx = game.players.findIndex(p => {
935 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
937 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
938 if (!game.chats) game.chats = []; //live games don't have chat history
939 if (gtype == "corr") {
940 if (game.players[0].color == "b") {
941 // Adopt the same convention for live and corr games: [0] = white
942 [game.players[0], game.players[1]] = [
947 // NOTE: clocks in seconds, initime in milliseconds
948 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
949 game.clocks = [tc.mainTime, tc.mainTime];
950 const L = game.moves.length;
951 if (game.score == "*") {
952 // Set clocks + initime
953 game.initime = [0, 0];
955 const gameLastupdate = game.moves[L-1].played;
956 game.initime[L % 2] = gameLastupdate;
959 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
963 // Sort chat messages from newest to oldest
964 game.chats.sort((c1, c2) => {
965 return c2.added - c1.added;
967 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
968 // Did a chat message arrive after my last move?
970 if (L == 1 && myIdx == 0)
971 dtLastMove = game.moves[0].played;
974 // It's now white turn
975 dtLastMove = game.moves[L-1-(1-myIdx)].played;
978 dtLastMove = game.moves[L-1-myIdx].played;
981 if (dtLastMove < game.chats[0].added)
982 document.getElementById("chatBtn").classList.add("somethingnew");
984 // Now that we used idx and played, re-format moves as for live games
985 game.moves = game.moves.map(m => m.squares);
987 if (gtype == "live" && game.clocks[0] < 0) {
989 game.clocks = [tc.mainTime, tc.mainTime];
990 if (game.score == "*") {
991 game.initime[0] = Date.now();
993 // I play in this live game; corr games don't have clocks+initime
994 GameStorage.update(game.id, {
996 initime: game.initime
1001 // TODO: merge next 2 "if" conditions
1002 if (!!game.drawOffer) {
1003 if (game.drawOffer == "t")
1004 // Three repetitions
1005 this.drawOffer = "threerep";
1007 // Draw offered by any of the players:
1008 if (myIdx < 0) this.drawOffer = "received";
1010 // I play in this game:
1012 (game.drawOffer == "w" && myIdx == 0) ||
1013 (game.drawOffer == "b" && myIdx == 1)
1015 this.drawOffer = "sent";
1016 else this.drawOffer = "received";
1020 if (!!game.rematchOffer) {
1021 if (myIdx < 0) this.rematchOffer = "received";
1023 // I play in this game:
1025 (game.rematchOffer == "w" && myIdx == 0) ||
1026 (game.rematchOffer == "b" && myIdx == 1)
1028 this.rematchOffer = "sent";
1029 else this.rematchOffer = "received";
1032 this.repeat = {}; //reset: scan past moves' FEN:
1034 let vr_tmp = new V(game.fenStart);
1036 game.moves.forEach(m => {
1037 playMove(m, vr_tmp);
1038 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
1039 this.repeat[fenIdx] = this.repeat[fenIdx]
1040 ? this.repeat[fenIdx] + 1
1043 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1044 this.game = Object.assign(
1045 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1048 increment: tc.increment,
1050 // opponent sid not strictly required (or available), but easier
1051 // at least oppsid or oppid is available anyway:
1052 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1053 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
1057 if (this.gameIsLoading)
1058 // Re-load game because we missed some moves:
1059 // artificially reset BaseGame (required if moves arrived in wrong order)
1060 this.$refs["basegame"].re_setVariables();
1063 this.gotMoveIdx = game.moves.length - 1;
1064 // If we arrive here after 'nextGame' action, the board might be hidden
1065 let boardDiv = document.querySelector(".game");
1066 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1067 boardDiv.style.visibility = "visible";
1069 this.re_setClocks();
1070 this.$nextTick(() => {
1071 this.game.rendered = true;
1072 // Did lastate arrive before game was rendered?
1073 if (this.lastate) this.processLastate();
1075 if (this.lastateAsked) {
1076 this.lastateAsked = false;
1077 this.sendLastate(game.oppsid);
1079 if (this.gameIsLoading) {
1080 this.gameIsLoading = false;
1081 if (this.gotMoveIdx >= game.moves.length)
1082 // Some moves arrived meanwhile...
1083 this.askGameAgain();
1085 if (!!callback) callback();
1088 afterRetrieval(game);
1091 if (this.gameRef.rid) {
1092 // Remote live game: forgetting about callback func... (TODO: design)
1093 this.send("askfullgame", { target: this.gameRef.rid });
1095 // Local or corr game on server.
1096 // NOTE: afterRetrieval() is never called if game not found
1097 const gid = this.gameRef.id;
1098 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
1099 // corr games identifiers are integers
1107 g.moves.forEach(m => {
1108 m.squares = JSON.parse(m.squares);
1117 GameStorage.get(this.gameRef.id, afterRetrieval);
1120 re_setClocks: function() {
1121 if (this.game.moves.length < 2 || this.game.score != "*") {
1122 // 1st move not completed yet, or game over: freeze time
1123 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1126 const currentTurn = this.vr.turn;
1127 const currentMovesCount = this.game.moves.length;
1128 const colorIdx = ["w", "b"].indexOf(currentTurn);
1130 this.game.clocks[colorIdx] -
1131 (Date.now() - this.game.initime[colorIdx]) / 1000;
1132 this.virtualClocks = [0, 1].map(i => {
1134 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
1135 return ppt(this.game.clocks[i] - removeTime).split(':');
1137 this.clockUpdate = setInterval(
1141 this.game.moves.length > currentMovesCount ||
1142 this.game.score != "*"
1144 clearInterval(this.clockUpdate);
1147 currentTurn == "w" ? "0-1" : "1-0",
1154 ppt(Math.max(0, --countdown)).split(':')
1160 // Update variables and storage after a move:
1161 processMove: function(move, data) {
1162 if (!data) data = {};
1163 const moveCol = this.vr.turn;
1164 const doProcessMove = () => {
1165 const colorIdx = ["w", "b"].indexOf(moveCol);
1166 const nextIdx = 1 - colorIdx;
1167 const origMovescount = this.game.moves.length;
1168 let addTime = 0; //for live games
1169 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1170 if (this.drawOffer == "received")
1172 this.drawOffer = "";
1173 if (this.game.type == "live" && origMovescount >= 2) {
1174 const elapsed = Date.now() - this.game.initime[colorIdx];
1175 // elapsed time is measured in milliseconds
1176 addTime = this.game.increment - elapsed / 1000;
1179 // Update current game object:
1180 playMove(move, this.vr);
1181 // The move is played: stop clock
1182 clearInterval(this.clockUpdate);
1184 // Received move, score has not been computed in BaseGame (!!noemit)
1185 const score = this.vr.getCurrentScore();
1186 if (score != "*") this.gameOver(score);
1188 // TODO: notifyTurn: "changeturn" message
1189 this.game.moves.push(move);
1190 this.game.fen = this.vr.getFen();
1191 if (this.game.type == "live") {
1192 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
1193 else this.game.clocks[colorIdx] += addTime;
1195 // In corr games, just reset clock to mainTime:
1197 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1199 // NOTE: opponent's initime is reset after "gotmove" is received
1201 !this.game.mycolor ||
1202 moveCol != this.game.mycolor ||
1203 !!data.receiveMyMove
1205 this.game.initime[nextIdx] = Date.now();
1207 // If repetition detected, consider that a draw offer was received:
1208 const fenObj = this.vr.getFenForRepeat();
1209 this.repeat[fenObj] =
1210 !!this.repeat[fenObj]
1211 ? this.repeat[fenObj] + 1
1213 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1214 else if (this.drawOffer == "threerep") this.drawOffer = "";
1215 if (!!this.game.mycolor && !data.receiveMyMove) {
1216 // NOTE: 'var' to see that variable outside this block
1217 var filtered_move = getFilteredMove(move);
1219 // Since corr games are stored at only one location, update should be
1220 // done only by one player for each move:
1222 !!this.game.mycolor &&
1223 !data.receiveMyMove &&
1224 (this.game.type == "live" || moveCol == this.game.mycolor)
1227 switch (this.drawOffer) {
1232 drawCode = this.game.mycolor;
1235 drawCode = V.GetOppCol(this.game.mycolor);
1238 if (this.game.type == "corr") {
1239 // corr: only move, fen and score
1240 this.updateCorrGame({
1243 squares: filtered_move,
1247 // Code "n" for "None" to force reset (otherwise it's ignored)
1248 drawOffer: drawCode || "n"
1252 const updateStorage = () => {
1253 GameStorage.update(this.gameRef.id, {
1255 move: filtered_move,
1256 moveIdx: origMovescount,
1257 clocks: this.game.clocks,
1258 initime: this.game.initime,
1262 // The active tab can update storage immediately
1263 if (!document.hidden) updateStorage();
1264 // Small random delay otherwise
1265 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1268 // Send move ("newmove" event) to people in the room (if our turn)
1269 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1271 move: filtered_move,
1272 index: origMovescount,
1273 // color is required to check if this is my move (if several tabs opened)
1275 cancelDrawOffer: this.drawOffer == ""
1277 if (this.game.type == "live")
1278 sendMove["clock"] = this.game.clocks[colorIdx];
1279 this.opponentGotMove = false;
1280 this.send("newmove", {data: sendMove});
1281 // If the opponent doesn't reply gotmove soon enough, re-send move:
1282 // Do this at most 2 times, because mpore would mean network issues,
1283 // opponent would then be expected to disconnect/reconnect.
1285 const currentUrl = document.location.href;
1286 this.retrySendmove = setInterval(
1290 this.opponentGotMove ||
1291 document.location.href != currentUrl //page change
1293 clearInterval(this.retrySendmove);
1296 const oppsid = this.getOppsid();
1298 // Opponent is disconnected: he'll ask last state
1299 clearInterval(this.retrySendmove);
1301 this.send("newmove", { data: sendMove, target: oppsid });
1309 // Not my move or I'm an observer: just start other player's clock
1310 this.re_setClocks();
1313 this.game.type == "corr" &&
1314 moveCol == this.game.mycolor &&
1317 let boardDiv = document.querySelector(".game");
1318 const afterSetScore = () => {
1320 if (this.st.settings.gotonext && this.nextIds.length > 0)
1321 this.showNextGame();
1323 // The board might have been hidden:
1324 if (boardDiv.style.visibility == "hidden")
1325 boardDiv.style.visibility = "visible";
1328 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1329 // We may play several moves in a row: in case of, remove listener:
1330 let elClone = el.cloneNode(true);
1331 el.parentNode.replaceChild(elClone, el);
1332 elClone.addEventListener(
1335 document.getElementById("modalConfirm").checked = false;
1336 if (!!data.score && data.score != "*")
1338 this.gameOver(data.score, null, afterSetScore);
1339 else afterSetScore();
1342 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1343 V.PlayOnBoard(this.vr.board, move);
1344 const position = this.vr.getBaseFen();
1345 V.UndoOnBoard(this.vr.board, move);
1346 if (["all","byrow"].includes(V.ShowMoves)) {
1347 this.curDiag = getDiagram({
1349 orientation: V.CanFlip ? this.game.mycolor : "w"
1351 document.querySelector("#confirmDiv > .card").style.width =
1352 boardDiv.offsetWidth + "px";
1354 // Incomplete information: just ask confirmation
1355 // Hide the board, because otherwise it could reveal infos
1356 boardDiv.style.visibility = "hidden";
1357 this.moveNotation = getFullNotation(move);
1359 document.getElementById("modalConfirm").checked = true;
1363 if (!!data.score && data.score != "*")
1364 this.gameOver(data.score, null, doProcessMove);
1365 else doProcessMove();
1368 cancelMove: function() {
1369 let boardDiv = document.querySelector(".game");
1370 if (boardDiv.style.visibility == "hidden")
1371 boardDiv.style.visibility = "visible";
1372 document.getElementById("modalConfirm").checked = false;
1373 this.$refs["basegame"].cancelLastMove();
1375 // In corr games, callback to change page only after score is set:
1376 gameOver: function(score, scoreMsg, callback) {
1377 this.game.score = score;
1378 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1379 this.game.scoreMsg = scoreMsg;
1380 this.$set(this.game, "scoreMsg", scoreMsg);
1381 const myIdx = this.game.players.findIndex(p => {
1382 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1385 // OK, I play in this game
1390 if (this.game.type == "live") {
1391 GameStorage.update(this.gameRef.id, scoreObj);
1392 if (!!callback) callback();
1394 else this.updateCorrGame(scoreObj, callback);
1395 // Notify the score to main Hall. TODO: only one player (currently double send)
1396 this.send("result", { gid: this.game.id, score: score });
1398 else if (!!callback) callback();
1404 <style lang="sass" scoped>
1410 background-color: lightgreen
1422 @media screen and (min-width: 768px)
1425 @media screen and (max-width: 767px)
1430 display: inline-block
1434 display: inline-block
1436 display: inline-flex
1440 @media screen and (max-width: 767px)
1443 @media screen and (max-width: 767px)
1446 @media screen and (min-width: 768px)
1458 background-color: #edda99
1460 display: inline-block
1469 display: inline-block
1482 animation: blink-animation 2s steps(3, start) infinite
1483 @keyframes blink-animation
1488 display: inline-block
1500 .draw-sent, .draw-sent:hover
1501 background-color: lightyellow
1503 .draw-received, .draw-received:hover
1504 background-color: lightgreen
1506 .draw-threerep, .draw-threerep:hover
1507 background-color: #e4d1fc
1509 .rematch-sent, .rematch-sent:hover
1510 background-color: lightyellow
1512 .rematch-received, .rematch-received:hover
1513 background-color: lightgreen
1516 background-color: #c5fefe
1529 background-color: lightgreen
1531 background-color: red