5 @click="resetChatColor()"
9 data-checkbox="modalChat"
12 label.modal-close(for="modalChat")
14 span {{ Object.keys(people).length + " " + st.tr["participant(s):"] }}
16 v-for="p in Object.values(people)"
20 span.anonymous(v-if="Object.values(people).some(p => !p.name && p.id === 0)")
24 :players="game.players"
25 :pastChats="game.chats"
28 @chatcleared="clearChat"
30 input#modalConfirm.modal(type="checkbox")
31 div#confirmDiv(role="dialog")
33 .diagram(v-html="curDiag")
34 .button-group#buttonsConfirm
35 // onClick for acceptBtn: set dynamically
37 span {{ st.tr["Validate"] }}
38 button.refuseBtn(@click="cancelMove()")
39 span {{ st.tr["Cancel"] }}
41 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
42 span.variant-cadence {{ game.cadence }}
43 span.variant-name {{ game.vname }}
45 v-if="nextIds.length > 0"
46 @click="showNextGame()"
48 | {{ st.tr["Next_g"] }}
49 button#chatBtn.tooltip(
50 onClick="window.doClick('modalChat')"
53 img(src="/images/icons/chat.svg")
54 #actions(v-if="game.score=='*'")
57 :class="{['draw-' + drawOffer]: true}"
58 :aria-label="st.tr['Draw']"
60 img(src="/images/icons/draw.svg")
64 :aria-label="st.tr['Abort']"
66 img(src="/images/icons/abort.svg")
70 :aria-label="st.tr['Resign']"
72 img(src="/images/icons/resign.svg")
74 v-else-if="!!game.mycolor"
76 :aria-label="st.tr['Rematch']"
78 img(src="/images/icons/rematch.svg")
81 span.name(:class="{connected: isConnected(0)}")
82 | {{ game.players[0].name || "@nonymous" }}
84 v-if="game.score=='*'"
85 :class="{yourturn: !!vr && vr.turn == 'w'}"
87 span.time-left {{ virtualClocks[0][0] }}
88 span.time-separator(v-if="!!virtualClocks[0][1]") :
89 span.time-right(v-if="!!virtualClocks[0][1]")
90 | {{ virtualClocks[0][1] }}
92 span.name(:class="{connected: isConnected(1)}")
93 | {{ game.players[1].name || "@nonymous" }}
95 v-if="game.score=='*'"
96 :class="{yourturn: !!vr && vr.turn == 'b'}"
98 span.time-left {{ virtualClocks[1][0] }}
99 span.time-separator(v-if="!!virtualClocks[1][1]") :
100 span.time-right(v-if="!!virtualClocks[1][1]")
101 | {{ virtualClocks[1][1] }}
105 @newmove="processMove"
110 import BaseGame from "@/components/BaseGame.vue";
111 import Chat from "@/components/Chat.vue";
112 import { store } from "@/store";
113 import { GameStorage } from "@/utils/gameStorage";
114 import { ppt } from "@/utils/datetime";
115 import { ajax } from "@/utils/ajax";
116 import { extractTime } from "@/utils/timeControl";
117 import { getRandString } from "@/utils/alea";
118 import { getScoreMessage } from "@/utils/scoring";
119 import { getFullNotation } from "@/utils/notation";
120 import { getDiagram } from "@/utils/printDiagram";
121 import { processModalClick } from "@/utils/modalClick";
122 import { playMove, getFilteredMove } from "@/utils/playUndo";
123 import { ArrayFun } from "@/utils/array";
124 import params from "@/parameters";
135 // rid = remote (socket) ID
140 game: {}, //passed to BaseGame
141 // virtualClocks will be initialized from true game.clocks
143 vr: null, //"variant rules" object initialized from FEN
145 people: {}, //players + observers
146 onMygames: [], //opponents (or me) on "MyGames" page
147 lastate: undefined, //used if opponent send lastate before game is ready
148 repeat: {}, //detect position repetition
149 curDiag: "", //for corr moves confirmation
152 roomInitialized: false,
153 // If newmove has wrong index: ask fullgame again:
155 gameIsLoading: false,
156 // If asklastate got no reply, ask again:
158 gotMoveIdx: -1, //last move index received
159 // If newmove got no pingback, send again:
160 opponentGotMove: false,
162 // Intervals from setInterval():
163 // TODO: limit them to e.g. 3 retries ?!
164 askIfPeerConnected: null,
168 // Related to (killing of) self multi-connects:
174 $route: function(to, from) {
175 if (from.params["id"] != to.params["id"]) {
176 // Change everything:
177 this.cleanBeforeDestroy();
178 let boardDiv = document.querySelector(".game");
180 // In case of incomplete information variant:
181 boardDiv.style.visibility = "hidden";
185 this.gameRef.id = to.params["id"];
186 this.gameRef.rid = to.query["rid"];
187 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
192 // NOTE: some redundant code with Hall.vue (mostly related to people array)
193 created: function() {
196 mounted: function() {
198 .getElementById("chatWrap")
199 .addEventListener("click", processModalClick);
200 if ("ontouchstart" in window) {
201 // Disable tooltips on smartphones:
202 document.getElementsByClassName("tooltip").forEach(elt => {
203 elt.classList.remove("tooltip");
207 beforeDestroy: function() {
208 this.cleanBeforeDestroy();
211 atCreation: function() {
212 // 0] (Re)Set variables
213 this.gameRef.id = this.$route.params["id"];
214 // rid = remote ID to find an observed live game,
215 // next = next corr games IDs to navigate faster
216 // (Both might be undefined)
217 this.gameRef.rid = this.$route.query["rid"];
218 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
219 // Always add myself to players' list
220 const my = this.st.user;
221 this.$set(this.people, my.sid, { id: my.id, name: my.name });
223 players: [{ name: "" }, { name: "" }],
227 let chatComp = this.$refs["chatcomp"];
228 if (!!chatComp) chatComp.chats = [];
229 this.virtualClocks = [[0,0], [0,0]];
233 this.lastate = undefined;
235 this.roomInitialized = false;
236 this.askGameTime = 0;
237 this.gameIsLoading = false;
238 this.gotLastate = false;
239 this.gotMoveIdx = -1;
240 this.opponentGotMove = false;
241 this.askIfPeerConnected = null;
242 this.askLastate = null;
243 this.retrySendmove = null;
244 this.clockUpdate = null;
245 this.newConnect = {};
247 // 1] Initialize connection
248 this.connexionString =
255 // Discard potential "/?next=[...]" for page indication:
256 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
257 this.conn = new WebSocket(this.connexionString);
258 this.conn.onmessage = this.socketMessageListener;
259 this.conn.onclose = this.socketCloseListener;
260 // Socket init required before loading remote game:
261 const socketInit = callback => {
262 if (!!this.conn && this.conn.readyState == 1)
266 // Socket not ready yet (initial loading)
267 // NOTE: it's important to call callback without arguments,
268 // otherwise first arg is Websocket object and loadGame fails.
269 this.conn.onopen = () => callback();
271 if (!this.gameRef.rid)
272 // Game stored locally or on server
273 this.loadGame(null, () => socketInit(this.roomInit));
275 // Game stored remotely: need socket to retrieve it
276 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
277 // --> It will be given when receiving "fullgame" socket event.
278 socketInit(this.loadGame);
280 cleanBeforeDestroy: function() {
281 if (!!this.askIfPeerConnected)
282 clearInterval(this.askIfPeerConnected);
283 if (!!this.askLastate)
284 clearInterval(this.askLastate);
285 if (!!this.retrySendmove)
286 clearInterval(this.retrySendmove);
287 if (!!this.clockUpdate)
288 clearInterval(this.clockUpdate);
289 this.send("disconnect");
291 roomInit: function() {
292 if (!this.roomInitialized) {
293 // Notify the room only now that I connected, because
294 // messages might be lost otherwise (if game loading is slow)
295 this.send("connect");
296 this.send("pollclients");
297 // We may ask fullgame several times if some moves are lost,
298 // but room should be init only once:
299 this.roomInitialized = true;
302 send: function(code, obj) {
304 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
306 isConnected: function(index) {
307 const player = this.game.players[index];
309 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
310 // Still have to check for name (because of potential multi-accounts
311 // on same browser, although this should be rare...)
312 return (!this.st.user.name || this.st.user.name == player.name);
313 // Try to find a match in people:
317 Object.keys(this.people).some(sid => sid == player.sid)
322 Object.values(this.people).some(p => p.id == player.uid)
326 resetChatColor: function() {
327 // TODO: this is called twice, once on opening an once on closing
328 document.getElementById("chatBtn").classList.remove("somethingnew");
330 processChat: function(chat) {
331 this.send("newchat", { data: chat });
332 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
333 if (this.game.type == "corr" && this.st.user.id > 0)
334 this.updateCorrGame({ chat: chat });
336 clearChat: function() {
337 // Nothing more to do if game is live (chats not recorded)
338 if (this.game.type == "corr") {
339 if (!!this.game.mycolor)
340 ajax("/chats", "DELETE", {gid: this.game.id});
341 this.$set(this.game, "chats", []);
344 // Notify turn after a new move (to opponent and me on MyGames page)
345 notifyTurn: function(sid) {
346 const player = this.people[sid];
347 const colorIdx = this.game.players.findIndex(
348 p => p.sid == sid || p.uid == player.id);
349 const color = ["w","b"][colorIdx];
350 const movesCount = this.game.moves.length;
352 (color == "w" && movesCount % 2 == 0) ||
353 (color == "b" && movesCount % 2 == 1);
354 this.send("turnchange", { target: sid, yourTurn: yourTurn });
356 showNextGame: function() {
357 // Did I play in current game? If not, add it to nextIds list
358 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
359 this.nextIds.unshift(this.game.id);
360 const nextGid = this.nextIds.pop();
362 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
364 rematch: function() {
365 alert("Unimplemented yet (soon :) )");
366 // TODO: same logic as for draw, but re-click remove rematch offer (toggle)
368 askGameAgain: function() {
369 this.gameIsLoading = true;
370 const currentUrl = document.location.href;
371 const doAskGame = () => {
372 if (currentUrl != document.location.href) return; //page change
373 if (!this.gameRef.rid)
374 // This is my game: just reload.
377 // Just ask fullgame again (once!), this is much simpler.
378 // If this fails, the user could just reload page :/
379 this.send("askfullgame", { target: this.gameRef.rid });
380 this.askIfPeerConnected = setInterval(
383 !!this.people[this.gameRef.rid] &&
384 currentUrl != document.location.href
386 this.send("askfullgame", { target: this.gameRef.rid });
387 clearInterval(this.askIfPeerConnected);
394 // Delay of at least 2s between two game requests
395 const now = Date.now();
396 const delay = Math.max(2000 - (now - this.askGameTime), 0);
397 this.askGameTime = now;
398 setTimeout(doAskGame, delay);
400 socketMessageListener: function(msg) {
401 if (!this.conn) return;
402 const data = JSON.parse(msg.data);
405 data.sockIds.forEach(sid => {
406 if (sid != this.st.user.sid)
407 this.send("askidentity", { target: sid });
411 if (!this.people[data.from]) {
412 this.newConnect[data.from] = true; //for self multi-connects tests
413 this.send("askidentity", { target: data.from });
417 this.$delete(this.people, data.from);
420 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
421 // Either me (another tab) or opponent
422 const sid = data.from;
423 if (!this.onMygames.some(s => s == sid))
425 this.onMygames.push(sid);
426 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
429 if (!this.people[sid])
430 this.send("askidentity", { target: sid });
433 ArrayFun.remove(this.onMygames, sid => sid == data.from);
436 // I logged in elsewhere:
438 alert(this.st.tr["New connexion detected: tab now offline"]);
440 case "askidentity": {
441 // Request for identification
443 // Decompose to avoid revealing email
444 name: this.st.user.name,
445 sid: this.st.user.sid,
448 this.send("identity", { data: me, target: data.from });
452 const user = data.data;
453 this.$set(this.people, user.sid, { name: user.name, id: user.id });
454 // If I multi-connect, kill current connexion if no mark (I'm older)
455 if (this.newConnect[user.sid]) {
458 user.id == this.st.user.id &&
459 user.sid != this.st.user.sid &&
460 !this.killed[this.st.user.sid]
462 this.send("killme", { sid: this.st.user.sid });
463 this.killed[this.st.user.sid] = true;
465 delete this.newConnect[user.sid];
467 if (!this.killed[this.st.user.sid]) {
468 // Ask potentially missed last state, if opponent and I play
470 !!this.game.mycolor &&
471 this.game.type == "live" &&
472 this.game.score == "*" &&
473 this.game.players.some(p => p.sid == user.sid)
475 this.send("asklastate", { target: user.sid });
476 this.askLastate = setInterval(
478 // Ask until we got a reply (or opponent disconnect):
479 if (!this.gotLastate && !!this.people[user.sid])
480 this.send("asklastate", { target: user.sid });
482 clearInterval(this.askLastate);
491 // Send current (live) game if not asked by any of the players
493 this.game.type == "live" &&
494 this.game.players.every(p => p.sid != data.from[0])
499 players: this.game.players,
501 cadence: this.game.cadence,
502 score: this.game.score,
503 rid: this.st.user.sid //useful in Hall if I'm an observer
505 this.send("game", { data: myGame, target: data.from });
509 const gameToSend = Object.keys(this.game)
512 "id","fen","players","vid","cadence","fenStart","vname",
513 "moves","clocks","initime","score","drawOffer"
517 obj[k] = this.game[k];
522 this.send("fullgame", { data: gameToSend, target: data.from });
525 // Callback "roomInit" to poll clients only after game is loaded
526 this.loadGame(data.data, this.roomInit);
529 // Sending informative last state if I played a move or score != "*"
531 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
532 this.game.score != "*" ||
533 this.drawOffer == "sent"
535 // Send our "last state" informations to opponent
536 const L = this.game.moves.length;
537 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
539 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
540 addTime: L > 0 ? this.game.addTimes[L - 1] : undefined,
541 // Since we played a move (or abort or resign),
542 // only drawOffer=="sent" is possible
543 drawSent: this.drawOffer == "sent",
544 score: this.game.score,
546 initime: this.game.initime[1 - myIdx] //relevant only if I played
548 this.send("lastate", { data: myLastate, target: data.from });
550 this.send("lastate", { data: {nothing: true}, target: data.from });
554 // Got opponent infos about last move
555 this.gotLastate = true;
556 if (!data.data.nothing) {
557 this.lastate = data.data;
558 if (this.game.rendered)
559 // Game is rendered (Board component)
560 this.processLastate();
561 // Else: will be processed when game is ready
566 const movePlus = data.data;
567 const movesCount = this.game.moves.length;
568 if (movePlus.index > movesCount) {
569 // This can only happen if I'm an observer and missed a move.
570 if (this.gotMoveIdx < movePlus.index)
571 this.gotMoveIdx = movePlus.index;
572 if (!this.gameIsLoading) this.askGameAgain();
576 movePlus.index < movesCount ||
577 this.gotMoveIdx >= movePlus.index
579 // Opponent re-send but we already have the move:
580 // (maybe he didn't receive our pingback...)
581 this.send("gotmove", {data: movePlus.index, target: data.from});
583 this.gotMoveIdx = movePlus.index;
584 const receiveMyMove = (movePlus.color == this.game.mycolor);
585 if (!receiveMyMove && !!this.game.mycolor)
586 // Notify opponent that I got the move:
587 this.send("gotmove", {data: movePlus.index, target: data.from});
588 if (movePlus.cancelDrawOffer) {
589 // Opponent refuses draw
591 // NOTE for corr games: drawOffer reset by player in turn
593 this.game.type == "live" &&
594 !!this.game.mycolor &&
597 GameStorage.update(this.gameRef.id, { drawOffer: "" });
600 this.$refs["basegame"].play(movePlus.move, "received", null, true);
604 addTime: movePlus.addTime,
605 receiveMyMove: receiveMyMove
613 this.opponentGotMove = true;
617 const score = data.side == "b" ? "1-0" : "0-1";
618 const side = data.side == "w" ? "White" : "Black";
619 this.gameOver(score, side + " surrender");
622 this.gameOver("?", "Stop");
625 this.gameOver("1/2", data.data);
628 // NOTE: observers don't know who offered draw
629 this.drawOffer = "received";
632 this.newChat = data.data;
633 if (!document.getElementById("modalChat").checked)
634 document.getElementById("chatBtn").classList.add("somethingnew");
638 socketCloseListener: function() {
639 this.conn = new WebSocket(this.connexionString);
640 this.conn.addEventListener("message", this.socketMessageListener);
641 this.conn.addEventListener("close", this.socketCloseListener);
643 updateCorrGame: function(obj, callback) {
648 gid: this.gameRef.id,
652 if (!!callback) callback();
656 // lastate was received, but maybe game wasn't ready yet:
657 processLastate: function() {
658 const data = this.lastate;
659 this.lastate = undefined; //security...
660 const L = this.game.moves.length;
661 if (data.movesCount > L) {
662 // Just got last move from him
663 this.$refs["basegame"].play(
667 {addTime: data.addTime, initime: data.initime}
670 if (data.drawSent) this.drawOffer = "received";
671 if (data.score != "*") {
673 if (this.game.score == "*")
674 // TODO: also pass scoreMsg in lastate
675 this.gameOver(data.score);
678 clickDraw: function() {
679 if (!this.game.mycolor) return; //I'm just spectator
680 if (["received", "threerep"].includes(this.drawOffer)) {
681 if (!confirm(this.st.tr["Accept draw?"])) return;
683 this.drawOffer == "received"
685 : "Three repetitions";
686 this.send("draw", { data: message });
687 this.gameOver("1/2", message);
688 } else if (this.drawOffer == "") {
689 // No effect if drawOffer == "sent"
690 if (this.game.mycolor != this.vr.turn) {
691 alert(this.st.tr["Draw offer only in your turn"]);
694 if (!confirm(this.st.tr["Offer draw?"])) return;
695 this.drawOffer = "sent";
696 this.send("drawoffer");
697 if (this.game.type == "live") {
700 { drawOffer: this.game.mycolor }
702 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
705 abortGame: function() {
706 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
707 this.gameOver("?", "Stop");
711 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
713 this.send("resign", { data: this.game.mycolor });
714 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
715 const side = this.game.mycolor == "w" ? "White" : "Black";
716 this.gameOver(score, side + " surrender");
718 // 3 cases for loading a game:
719 // - from indexedDB (running or completed live game I play)
720 // - from server (one correspondance game I play[ed] or not)
721 // - from remote peer (one live game I don't play, finished or not)
722 loadGame: function(game, callback) {
723 const afterRetrieval = async game => {
724 const vModule = await import("@/variants/" + game.vname + ".js");
725 window.V = vModule.VariantRules;
726 this.vr = new V(game.fen);
727 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
728 const tc = extractTime(game.cadence);
729 const myIdx = game.players.findIndex(p => {
730 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
732 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
733 if (!game.chats) game.chats = []; //live games don't have chat history
734 if (gtype == "corr") {
735 if (game.players[0].color == "b") {
736 // Adopt the same convention for live and corr games: [0] = white
737 [game.players[0], game.players[1]] = [
742 // NOTE: clocks in seconds, initime in milliseconds
743 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
744 game.clocks = [tc.mainTime, tc.mainTime];
745 const L = game.moves.length;
746 if (game.score == "*") {
747 // Set clocks + initime
748 game.initime = [0, 0];
750 const gameLastupdate = game.moves[L-1].played;
751 game.initime[L % 2] = gameLastupdate;
754 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
758 // Sort chat messages from newest to oldest
759 game.chats.sort((c1, c2) => {
760 return c2.added - c1.added;
762 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
763 // Did a chat message arrive after my last move?
765 if (L == 1 && myIdx == 0)
766 dtLastMove = game.moves[0].played;
769 // It's now white turn
770 dtLastMove = game.moves[L-1-(1-myIdx)].played;
773 dtLastMove = game.moves[L-1-myIdx].played;
776 if (dtLastMove < game.chats[0].added)
777 document.getElementById("chatBtn").classList.add("somethingnew");
779 // Now that we used idx and played, re-format moves as for live games
780 game.moves = game.moves.map(m => m.squares);
782 if (gtype == "live" && game.clocks[0] < 0) {
784 game.clocks = [tc.mainTime, tc.mainTime];
785 if (game.score == "*") {
786 game.initime[0] = Date.now();
788 // I play in this live game; corr games don't have clocks+initime
789 GameStorage.update(game.id, {
791 initime: game.initime
796 if (!!game.drawOffer) {
797 if (game.drawOffer == "t")
799 this.drawOffer = "threerep";
801 // Draw offered by any of the players:
802 if (myIdx < 0) this.drawOffer = "received";
804 // I play in this game:
806 (game.drawOffer == "w" && myIdx == 0) ||
807 (game.drawOffer == "b" && myIdx == 1)
809 this.drawOffer = "sent";
810 else this.drawOffer = "received";
814 this.repeat = {}; //reset: scan past moves' FEN:
816 let vr_tmp = new V(game.fenStart);
818 game.moves.forEach(m => {
820 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
821 this.repeat[fenIdx] = this.repeat[fenIdx]
822 ? this.repeat[fenIdx] + 1
825 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
826 this.game = Object.assign(
827 // NOTE: assign mycolor here, since BaseGame could also be VS computer
830 increment: tc.increment,
832 // opponent sid not strictly required (or available), but easier
833 // at least oppsid or oppid is available anyway:
834 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
835 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
836 addTimes: [], //used for live games
840 if (this.gameIsLoading)
841 // Re-load game because we missed some moves:
842 // artificially reset BaseGame (required if moves arrived in wrong order)
843 this.$refs["basegame"].re_setVariables();
846 this.gotMoveIdx = game.moves.length - 1;
847 // If we arrive here after 'nextGame' action, the board might be hidden
848 let boardDiv = document.querySelector(".game");
849 if (!!boardDiv && boardDiv.style.visibility == "hidden")
850 boardDiv.style.visibility = "visible";
853 this.$nextTick(() => {
854 this.game.rendered = true;
855 // Did lastate arrive before game was rendered?
856 if (this.lastate) this.processLastate();
858 if (this.gameIsLoading) {
859 this.gameIsLoading = false;
860 if (this.gotMoveIdx >= game.moves.length)
861 // Some moves arrived meanwhile...
864 if (!!callback) callback();
867 afterRetrieval(game);
870 if (this.gameRef.rid) {
871 // Remote live game: forgetting about callback func... (TODO: design)
872 this.send("askfullgame", { target: this.gameRef.rid });
874 // Local or corr game on server.
875 // NOTE: afterRetrieval() is never called if game not found
876 const gid = this.gameRef.id;
877 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
878 // corr games identifiers are integers
879 ajax("/games", "GET", { gid: gid }, res => {
881 g.moves.forEach(m => {
882 m.squares = JSON.parse(m.squares);
889 GameStorage.get(this.gameRef.id, afterRetrieval);
892 re_setClocks: function() {
893 if (this.game.moves.length < 2 || this.game.score != "*") {
894 // 1st move not completed yet, or game over: freeze time
895 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
898 clearInterval(this.clockUpdate);
899 const currentTurn = this.vr.turn;
900 const currentMovesCount = this.game.moves.length;
901 const colorIdx = ["w", "b"].indexOf(currentTurn);
903 this.game.clocks[colorIdx] -
904 (Date.now() - this.game.initime[colorIdx]) / 1000;
905 this.virtualClocks = [0, 1].map(i => {
907 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
908 return ppt(this.game.clocks[i] - removeTime).split(':');
910 this.clockUpdate = setInterval(() => {
913 this.game.moves.length > currentMovesCount ||
914 this.game.score != "*"
916 clearInterval(this.clockUpdate);
919 currentTurn == "w" ? "0-1" : "1-0",
926 ppt(Math.max(0, --countdown)).split(':')
930 // Update variables and storage after a move:
931 processMove: function(move, data) {
932 if (!data) data = {};
933 const moveCol = this.vr.turn;
934 const doProcessMove = () => {
935 const colorIdx = ["w", "b"].indexOf(moveCol);
936 const nextIdx = 1 - colorIdx;
937 const origMovescount = this.game.moves.length;
939 this.game.type == "live"
940 ? (data.addTime || 0)
942 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
943 if (this.drawOffer == "received")
946 if (this.game.type == "live" && origMovescount >= 2) {
947 const elapsed = Date.now() - this.game.initime[colorIdx];
948 // elapsed time is measured in milliseconds
949 addTime = this.game.increment - elapsed / 1000;
952 // Update current game object:
953 playMove(move, this.vr);
955 // Received move, score has not been computed in BaseGame (!!noemit)
956 const score = this.vr.getCurrentScore();
957 if (score != "*") this.gameOver(score);
959 // TODO: notifyTurn: "changeturn" message
960 this.game.moves.push(move);
961 // (add)Time indication: useful in case of lastate infos requested
962 if (this.game.type == "live")
963 this.game.addTimes.push(addTime);
964 this.game.fen = this.vr.getFen();
965 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
966 // In corr games, just reset clock to mainTime:
967 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
968 // data.initime is set only when I receive a "lastate" move from opponent
969 this.game.initime[nextIdx] = data.initime || Date.now();
970 // If repetition detected, consider that a draw offer was received:
971 const fenObj = this.vr.getFenForRepeat();
972 this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1;
973 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
974 else if (this.drawOffer == "threerep") this.drawOffer = "";
975 if (!!this.game.mycolor && !data.receiveMyMove) {
976 // NOTE: 'var' to see that variable outside this block
977 var filtered_move = getFilteredMove(move);
979 // Since corr games are stored at only one location, update should be
980 // done only by one player for each move:
982 !!this.game.mycolor &&
983 !data.receiveMyMove &&
984 (this.game.type == "live" || moveCol == this.game.mycolor)
987 switch (this.drawOffer) {
992 drawCode = this.game.mycolor;
995 drawCode = V.GetOppCol(this.game.mycolor);
998 if (this.game.type == "corr") {
999 // corr: only move, fen and score
1000 this.updateCorrGame({
1003 squares: filtered_move,
1007 // Code "n" for "None" to force reset (otherwise it's ignored)
1008 drawOffer: drawCode || "n"
1012 const updateStorage = () => {
1013 GameStorage.update(this.gameRef.id, {
1015 move: filtered_move,
1016 moveIdx: origMovescount,
1017 clocks: this.game.clocks,
1018 initime: this.game.initime,
1022 // The active tab can update storage immediately
1023 if (!document.hidden) updateStorage();
1024 // Small random delay otherwise
1025 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1028 // Send move ("newmove" event) to people in the room (if our turn)
1029 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1031 move: filtered_move,
1032 index: origMovescount,
1033 // color is required to check if this is my move (if several tabs opened)
1035 addTime: addTime, //undefined for corr games
1036 cancelDrawOffer: this.drawOffer == ""
1038 this.opponentGotMove = false;
1039 this.send("newmove", {data: sendMove});
1040 // If the opponent doesn't reply gotmove soon enough, re-send move:
1041 this.retrySendmove = setInterval(
1043 if (this.opponentGotMove) {
1044 clearInterval(this.retrySendmove);
1047 let oppsid = this.game.players[nextIdx].sid;
1049 oppsid = Object.keys(this.people).find(
1050 sid => this.people[sid].id == this.game.players[nextIdx].uid
1053 if (!oppsid || !this.people[oppsid])
1054 // Opponent is disconnected: he'll ask last state
1055 clearInterval(this.retrySendmove);
1056 else this.send("newmove", {data: sendMove, target: oppsid});
1063 this.game.type == "corr" &&
1064 moveCol == this.game.mycolor &&
1067 const afterSetScore = () => {
1069 if (this.st.settings.gotonext && this.nextIds.length > 0)
1070 this.showNextGame();
1072 this.re_setClocks();
1073 // The board might have been hidden:
1074 let boardDiv = document.querySelector(".game");
1075 if (boardDiv.style.visibility == "hidden")
1076 boardDiv.style.visibility = "visible";
1079 if (["all","byrow"].includes(V.ShowMoves)) {
1080 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1081 // We may play several moves in a row: in case of, remove listener:
1082 let elClone = el.cloneNode(true);
1083 el.parentNode.replaceChild(elClone, el);
1084 elClone.addEventListener(
1087 document.getElementById("modalConfirm").checked = false;
1088 if (!!data.score && data.score != "*")
1090 this.gameOver(data.score, null, afterSetScore);
1091 else afterSetScore();
1094 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1095 V.PlayOnBoard(this.vr.board, move);
1096 const position = this.vr.getBaseFen();
1097 V.UndoOnBoard(this.vr.board, move);
1098 this.curDiag = getDiagram({
1100 orientation: V.CanFlip ? this.game.mycolor : "w"
1102 document.getElementById("modalConfirm").checked = true;
1104 // Incomplete information: just ask confirmation
1105 // Hide the board, because otherwise it could be revealed (TODO?)
1106 let boardDiv = document.querySelector(".game");
1107 boardDiv.style.visibility = "hidden";
1110 this.st.tr["Move played:"] + " " +
1111 getFullNotation(move) + "\n" +
1112 this.st.tr["Are you sure?"]
1115 this.$refs["basegame"].cancelLastMove();
1116 boardDiv.style.visibility = "visible";
1119 if (!!data.score && data.score != "*")
1120 this.gameOver(data.score, null, afterSetScore);
1121 else afterSetScore();
1126 const afterSetScore = () => {
1128 this.re_setClocks();
1130 if (!!data.score && data.score != "*")
1131 this.gameOver(data.score, null, afterSetScore);
1132 else afterSetScore();
1135 cancelMove: function() {
1136 document.getElementById("modalConfirm").checked = false;
1137 this.$refs["basegame"].cancelLastMove();
1139 // In corr games, callback to change page only after score is set:
1140 gameOver: function(score, scoreMsg, callback) {
1141 this.game.score = score;
1142 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1143 this.$set(this.game, "scoreMsg", scoreMsg);
1144 const myIdx = this.game.players.findIndex(p => {
1145 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1148 // OK, I play in this game
1153 if (this.game.type == "live") {
1154 GameStorage.update(this.gameRef.id, scoreObj);
1155 if (!!callback) callback();
1157 else this.updateCorrGame(scoreObj, callback);
1158 // Notify the score to main Hall. TODO: only one player (currently double send)
1159 this.send("result", { gid: this.game.id, score: score });
1161 else if (!!callback) callback();
1167 <style lang="sass" scoped>
1169 background-color: lightgreen
1181 @media screen and (min-width: 768px)
1184 @media screen and (max-width: 767px)
1189 display: inline-block
1193 display: inline-block
1195 display: inline-flex
1199 @media screen and (max-width: 767px)
1202 @media screen and (max-width: 767px)
1205 @media screen and (min-width: 768px)
1217 background-color: #edda99
1219 display: inline-block
1228 display: inline-block
1241 animation: blink-animation 2s steps(3, start) infinite
1242 @keyframes blink-animation
1247 display: inline-block
1259 .draw-sent, .draw-sent:hover
1260 background-color: lightyellow
1262 .draw-received, .draw-received:hover
1263 background-color: lightgreen
1265 .draw-threerep, .draw-threerep:hover
1266 background-color: #e4d1fc
1269 background-color: #c5fefe
1274 // width: 100% required for Firefox
1284 background-color: lightgreen
1286 background-color: red