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)"
17 v-if="p.focus && !!p.name"
21 v-if="Object.values(people).some(p => p.focus && !p.name)"
26 :players="game.players"
27 :pastChats="game.chats"
30 @chatcleared="clearChat"
32 input#modalConfirm.modal(type="checkbox")
33 div#confirmDiv(role="dialog")
36 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
40 span {{ st.tr["Move played:"] + " " }}
41 span.bold {{ moveNotation }}
43 span {{ st.tr["Are you sure?"] }}
44 .button-group#buttonsConfirm
45 // onClick for acceptBtn: set dynamically
47 span {{ st.tr["Validate"] }}
48 button.refuseBtn(@click="cancelMove()")
49 span {{ st.tr["Cancel"] }}
51 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
52 span.variant-cadence {{ game.cadence }}
53 span.variant-name {{ game.vname }}
55 v-if="nextIds.length > 0"
56 @click="showNextGame()"
58 | {{ st.tr["Next_g"] }}
59 button#chatBtn.tooltip(
60 onClick="window.doClick('modalChat')"
63 img(src="/images/icons/chat.svg")
64 #actions(v-if="game.score=='*'")
67 :class="{['draw-' + drawOffer]: true}"
68 :aria-label="st.tr['Draw']"
70 img(src="/images/icons/draw.svg")
74 :aria-label="st.tr['Abort']"
76 img(src="/images/icons/abort.svg")
80 :aria-label="st.tr['Resign']"
82 img(src="/images/icons/resign.svg")
84 v-else-if="!!game.mycolor"
86 :aria-label="st.tr['Rematch']"
88 img(src="/images/icons/rematch.svg")
91 span.name(:class="{connected: isConnected(0)}")
92 | {{ game.players[0].name || "@nonymous" }}
94 v-if="game.score=='*'"
95 :class="{yourturn: !!vr && vr.turn == 'w'}"
97 span.time-left {{ virtualClocks[0][0] }}
98 span.time-separator(v-if="!!virtualClocks[0][1]") :
99 span.time-right(v-if="!!virtualClocks[0][1]")
100 | {{ virtualClocks[0][1] }}
102 span.name(:class="{connected: isConnected(1)}")
103 | {{ game.players[1].name || "@nonymous" }}
105 v-if="game.score=='*'"
106 :class="{yourturn: !!vr && vr.turn == 'b'}"
108 span.time-left {{ virtualClocks[1][0] }}
109 span.time-separator(v-if="!!virtualClocks[1][1]") :
110 span.time-right(v-if="!!virtualClocks[1][1]")
111 | {{ virtualClocks[1][1] }}
115 @newmove="processMove"
120 import BaseGame from "@/components/BaseGame.vue";
121 import Chat from "@/components/Chat.vue";
122 import { store } from "@/store";
123 import { GameStorage } from "@/utils/gameStorage";
124 import { ppt } from "@/utils/datetime";
125 import { ajax } from "@/utils/ajax";
126 import { extractTime } from "@/utils/timeControl";
127 import { getRandString } from "@/utils/alea";
128 import { getScoreMessage } from "@/utils/scoring";
129 import { getFullNotation } from "@/utils/notation";
130 import { getDiagram } from "@/utils/printDiagram";
131 import { processModalClick } from "@/utils/modalClick";
132 import { playMove, getFilteredMove } from "@/utils/playUndo";
133 import { ArrayFun } from "@/utils/array";
134 import params from "@/parameters";
145 // rid = remote (socket) ID
150 game: {}, //passed to BaseGame
151 // virtualClocks will be initialized from true game.clocks
153 vr: null, //"variant rules" object initialized from FEN
155 people: {}, //players + observers
156 onMygames: [], //opponents (or me) on "MyGames" page
157 lastate: undefined, //used if opponent send lastate before game is ready
158 repeat: {}, //detect position repetition
159 curDiag: "", //for corr moves confirmation
162 roomInitialized: false,
163 // If newmove has wrong index: ask fullgame again:
165 gameIsLoading: false,
166 // If asklastate got no reply, ask again:
168 gotMoveIdx: -1, //last move index received
169 // If newmove got no pingback, send again:
170 opponentGotMove: false,
172 // Incomplete info games: show move played
174 // Intervals from setInterval():
178 // Related to (killing of) self multi-connects:
184 $route: function(to, from) {
185 if (from.params["id"] != to.params["id"]) {
186 // Change everything:
187 this.cleanBeforeDestroy();
188 let boardDiv = document.querySelector(".game");
190 // In case of incomplete information variant:
191 boardDiv.style.visibility = "hidden";
195 this.gameRef.id = to.params["id"];
196 this.gameRef.rid = to.query["rid"];
197 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
202 // NOTE: some redundant code with Hall.vue (mostly related to people array)
203 created: function() {
206 mounted: function() {
207 document.addEventListener('visibilitychange', this.visibilityChange);
209 .getElementById("chatWrap")
210 .addEventListener("click", processModalClick);
211 if ("ontouchstart" in window) {
212 // Disable tooltips on smartphones:
213 document.getElementsByClassName("tooltip").forEach(elt => {
214 elt.classList.remove("tooltip");
218 beforeDestroy: function() {
219 document.removeEventListener('visibilitychange', this.visibilityChange);
220 this.cleanBeforeDestroy();
223 visibilityChange: function() {
224 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
226 document.visibilityState == "visible"
231 atCreation: function() {
232 // 0] (Re)Set variables
233 this.gameRef.id = this.$route.params["id"];
234 // rid = remote ID to find an observed live game,
235 // next = next corr games IDs to navigate faster
236 // (Both might be undefined)
237 this.gameRef.rid = this.$route.query["rid"];
238 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
239 // Always add myself to players' list
240 const my = this.st.user;
251 players: [{ name: "" }, { name: "" }],
255 let chatComp = this.$refs["chatcomp"];
256 if (!!chatComp) chatComp.chats = [];
257 this.virtualClocks = [[0,0], [0,0]];
261 this.lastate = undefined;
263 this.roomInitialized = false;
264 this.askGameTime = 0;
265 this.gameIsLoading = false;
266 this.gotLastate = false;
267 this.gotMoveIdx = -1;
268 this.opponentGotMove = false;
269 this.askLastate = null;
270 this.retrySendmove = null;
271 this.clockUpdate = null;
272 this.newConnect = {};
274 // 1] Initialize connection
275 this.connexionString =
282 // Discard potential "/?next=[...]" for page indication:
283 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
284 this.conn = new WebSocket(this.connexionString);
285 this.conn.onmessage = this.socketMessageListener;
286 this.conn.onclose = this.socketCloseListener;
287 // Socket init required before loading remote game:
288 const socketInit = callback => {
289 if (!!this.conn && this.conn.readyState == 1)
293 // Socket not ready yet (initial loading)
294 // NOTE: it's important to call callback without arguments,
295 // otherwise first arg is Websocket object and loadGame fails.
296 this.conn.onopen = () => callback();
298 if (!this.gameRef.rid)
299 // Game stored locally or on server
300 this.loadGame(null, () => socketInit(this.roomInit));
302 // Game stored remotely: need socket to retrieve it
303 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
304 // --> It will be given when receiving "fullgame" socket event.
305 socketInit(this.loadGame);
307 cleanBeforeDestroy: function() {
308 if (!!this.askLastate)
309 clearInterval(this.askLastate);
310 if (!!this.retrySendmove)
311 clearInterval(this.retrySendmove);
312 if (!!this.clockUpdate)
313 clearInterval(this.clockUpdate);
314 this.send("disconnect");
316 roomInit: function() {
317 if (!this.roomInitialized) {
318 // Notify the room only now that I connected, because
319 // messages might be lost otherwise (if game loading is slow)
320 this.send("connect");
321 this.send("pollclients");
322 // We may ask fullgame several times if some moves are lost,
323 // but room should be init only once:
324 this.roomInitialized = true;
327 send: function(code, obj) {
329 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
331 isConnected: function(index) {
332 const player = this.game.players[index];
333 // Is it me ? In this case no need to bother with focus
334 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
335 // Still have to check for name (because of potential multi-accounts
336 // on same browser, although this should be rare...)
337 return (!this.st.user.name || this.st.user.name == player.name);
338 // Try to find a match in people:
342 Object.keys(this.people).some(sid =>
343 sid == player.sid && this.people[sid].focus)
348 Object.values(this.people).some(p =>
349 p.id == player.uid && p.focus)
353 resetChatColor: function() {
354 // TODO: this is called twice, once on opening an once on closing
355 document.getElementById("chatBtn").classList.remove("somethingnew");
357 processChat: function(chat) {
358 this.send("newchat", { data: chat });
359 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
360 if (this.game.type == "corr" && this.st.user.id > 0)
361 this.updateCorrGame({ chat: chat });
363 clearChat: function() {
364 // Nothing more to do if game is live (chats not recorded)
365 if (this.game.type == "corr") {
366 if (!!this.game.mycolor) {
370 { data: { gid: this.game.id } }
373 this.$set(this.game, "chats", []);
376 // Notify turn after a new move (to opponent and me on MyGames page)
377 notifyTurn: function(sid) {
378 const player = this.people[sid];
379 const colorIdx = this.game.players.findIndex(
380 p => p.sid == sid || p.uid == player.id);
381 const color = ["w","b"][colorIdx];
382 const movesCount = this.game.moves.length;
384 (color == "w" && movesCount % 2 == 0) ||
385 (color == "b" && movesCount % 2 == 1);
386 this.send("turnchange", { target: sid, yourTurn: yourTurn });
388 showNextGame: function() {
389 // Did I play in current game? If not, add it to nextIds list
390 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
391 this.nextIds.unshift(this.game.id);
392 const nextGid = this.nextIds.pop();
394 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
396 rematch: function() {
397 alert("Unimplemented yet (soon :) )");
398 // TODO: same logic as for draw, but re-click remove rematch offer (toggle)
400 askGameAgain: function() {
401 this.gameIsLoading = true;
402 const currentUrl = document.location.href;
403 const doAskGame = () => {
404 if (document.location.href != currentUrl) return; //page change
405 if (!this.gameRef.rid)
406 // This is my game: just reload.
409 // Just ask fullgame again (once!), this is much simpler.
410 // If this fails, the user could just reload page :/
411 this.send("askfullgame", { target: this.gameRef.rid });
413 // Delay of at least 2s between two game requests
414 const now = Date.now();
415 const delay = Math.max(2000 - (now - this.askGameTime), 0);
416 this.askGameTime = now;
417 setTimeout(doAskGame, delay);
419 socketMessageListener: function(msg) {
420 if (!this.conn) return;
421 const data = JSON.parse(msg.data);
424 data.sockIds.forEach(sid => {
425 if (sid != this.st.user.sid) {
426 this.people[sid] = { focus: true };
427 this.send("askidentity", { target: sid });
432 if (!this.people[data.from]) {
433 this.people[data.from] = { focus: true };
434 this.newConnect[data.from] = true; //for self multi-connects tests
435 this.send("askidentity", { target: data.from });
439 this.$delete(this.people, data.from);
442 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
443 // Either me (another tab) or opponent
444 const sid = data.from;
445 if (!this.onMygames.some(s => s == sid))
447 this.onMygames.push(sid);
448 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
451 if (!this.people[sid])
452 this.send("askidentity", { target: sid });
455 ArrayFun.remove(this.onMygames, sid => sid == data.from);
458 let player = this.people[data.from];
461 this.$forceUpdate(); //TODO: shouldn't be required
466 let player = this.people[data.from];
468 player.focus = false;
469 this.$forceUpdate(); //TODO: shouldn't be required
474 // I logged in elsewhere:
476 alert(this.st.tr["New connexion detected: tab now offline"]);
478 case "askidentity": {
479 // Request for identification
481 // Decompose to avoid revealing email
482 name: this.st.user.name,
483 sid: this.st.user.sid,
486 this.send("identity", { data: me, target: data.from });
490 const user = data.data;
491 let player = this.people[user.sid];
492 // player.focus is already set
493 player.name = user.name;
495 this.$forceUpdate(); //TODO: shouldn't be required
496 // If I multi-connect, kill current connexion if no mark (I'm older)
497 if (this.newConnect[user.sid]) {
500 user.id == this.st.user.id &&
501 user.sid != this.st.user.sid &&
502 !this.killed[this.st.user.sid]
504 this.send("killme", { sid: this.st.user.sid });
505 this.killed[this.st.user.sid] = true;
507 delete this.newConnect[user.sid];
509 if (!this.killed[this.st.user.sid]) {
510 // Ask potentially missed last state, if opponent and I play
512 !!this.game.mycolor &&
513 this.game.type == "live" &&
514 this.game.score == "*" &&
515 this.game.players.some(p => p.sid == user.sid)
517 this.send("asklastate", { target: user.sid });
519 this.askLastate = setInterval(
521 // Ask at most 3 times:
522 // if no reply after that there should be a network issue.
526 !!this.people[user.sid]
528 this.send("asklastate", { target: user.sid });
531 clearInterval(this.askLastate);
541 // Send current (live) game if not asked by any of the players
543 this.game.type == "live" &&
544 this.game.players.every(p => p.sid != data.from[0])
549 players: this.game.players,
551 cadence: this.game.cadence,
552 score: this.game.score,
553 rid: this.st.user.sid //useful in Hall if I'm an observer
555 this.send("game", { data: myGame, target: data.from });
559 const gameToSend = Object.keys(this.game)
562 "id","fen","players","vid","cadence","fenStart","vname",
563 "moves","clocks","initime","score","drawOffer"
567 obj[k] = this.game[k];
572 this.send("fullgame", { data: gameToSend, target: data.from });
575 // Callback "roomInit" to poll clients only after game is loaded
576 this.loadGame(data.data, this.roomInit);
579 // Sending informative last state if I played a move or score != "*"
581 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
582 this.game.score != "*" ||
583 this.drawOffer == "sent"
585 // Send our "last state" informations to opponent
586 const L = this.game.moves.length;
587 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
589 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
590 clock: this.game.clocks[myIdx],
591 // Since we played a move (or abort or resign),
592 // only drawOffer=="sent" is possible
593 drawSent: this.drawOffer == "sent",
594 score: this.game.score,
595 score: this.game.scoreMsg,
597 initime: this.game.initime[1 - myIdx] //relevant only if I played
599 this.send("lastate", { data: myLastate, target: data.from });
601 this.send("lastate", { data: {nothing: true}, target: data.from });
605 // Got opponent infos about last move
606 this.gotLastate = true;
607 if (!data.data.nothing) {
608 this.lastate = data.data;
609 if (this.game.rendered)
610 // Game is rendered (Board component)
611 this.processLastate();
612 // Else: will be processed when game is ready
617 const movePlus = data.data;
618 const movesCount = this.game.moves.length;
619 if (movePlus.index > movesCount) {
620 // This can only happen if I'm an observer and missed a move.
621 if (this.gotMoveIdx < movePlus.index)
622 this.gotMoveIdx = movePlus.index;
623 if (!this.gameIsLoading) this.askGameAgain();
627 movePlus.index < movesCount ||
628 this.gotMoveIdx >= movePlus.index
630 // Opponent re-send but we already have the move:
631 // (maybe he didn't receive our pingback...)
632 this.send("gotmove", {data: movePlus.index, target: data.from});
634 this.gotMoveIdx = movePlus.index;
635 const receiveMyMove = (movePlus.color == this.game.mycolor);
636 if (!receiveMyMove && !!this.game.mycolor)
637 // Notify opponent that I got the move:
638 this.send("gotmove", {data: movePlus.index, target: data.from});
639 if (movePlus.cancelDrawOffer) {
640 // Opponent refuses draw
642 // NOTE for corr games: drawOffer reset by player in turn
644 this.game.type == "live" &&
645 !!this.game.mycolor &&
648 GameStorage.update(this.gameRef.id, { drawOffer: "" });
651 this.$refs["basegame"].play(movePlus.move, "received", null, true);
655 clock: movePlus.clock,
656 receiveMyMove: receiveMyMove
664 this.opponentGotMove = true;
665 // Now his clock starts running:
666 const oppIdx = ['w','b'].indexOf(this.vr.turn);
667 this.game.initime[oppIdx] = Date.now();
672 const score = data.side == "b" ? "1-0" : "0-1";
673 const side = data.side == "w" ? "White" : "Black";
674 this.gameOver(score, side + " surrender");
677 this.gameOver("?", "Stop");
680 this.gameOver("1/2", data.data);
683 // NOTE: observers don't know who offered draw
684 this.drawOffer = "received";
687 this.newChat = data.data;
688 if (!document.getElementById("modalChat").checked)
689 document.getElementById("chatBtn").classList.add("somethingnew");
693 socketCloseListener: function() {
694 this.conn = new WebSocket(this.connexionString);
695 this.conn.addEventListener("message", this.socketMessageListener);
696 this.conn.addEventListener("close", this.socketCloseListener);
698 updateCorrGame: function(obj, callback) {
704 gid: this.gameRef.id,
708 if (!!callback) callback();
713 // lastate was received, but maybe game wasn't ready yet:
714 processLastate: function() {
715 const data = this.lastate;
716 this.lastate = undefined; //security...
717 const L = this.game.moves.length;
718 if (data.movesCount > L) {
719 // Just got last move from him
720 this.$refs["basegame"].play(data.lastMove, "received", null, true);
721 this.processMove(data.lastMove, { clock: data.clock });
723 if (data.drawSent) this.drawOffer = "received";
724 if (data.score != "*") {
726 if (this.game.score == "*")
727 this.gameOver(data.score, data.scoreMsg);
730 clickDraw: function() {
731 if (!this.game.mycolor) return; //I'm just spectator
732 if (["received", "threerep"].includes(this.drawOffer)) {
733 if (!confirm(this.st.tr["Accept draw?"])) return;
735 this.drawOffer == "received"
737 : "Three repetitions";
738 this.send("draw", { data: message });
739 this.gameOver("1/2", message);
740 } else if (this.drawOffer == "") {
741 // No effect if drawOffer == "sent"
742 if (this.game.mycolor != this.vr.turn) {
743 alert(this.st.tr["Draw offer only in your turn"]);
746 if (!confirm(this.st.tr["Offer draw?"])) return;
747 this.drawOffer = "sent";
748 this.send("drawoffer");
749 if (this.game.type == "live") {
752 { drawOffer: this.game.mycolor }
754 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
757 abortGame: function() {
758 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
759 this.gameOver("?", "Stop");
763 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
765 this.send("resign", { data: this.game.mycolor });
766 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
767 const side = this.game.mycolor == "w" ? "White" : "Black";
768 this.gameOver(score, side + " surrender");
770 // 3 cases for loading a game:
771 // - from indexedDB (running or completed live game I play)
772 // - from server (one correspondance game I play[ed] or not)
773 // - from remote peer (one live game I don't play, finished or not)
774 loadGame: function(game, callback) {
775 const afterRetrieval = async game => {
776 const vModule = await import("@/variants/" + game.vname + ".js");
777 window.V = vModule.VariantRules;
778 this.vr = new V(game.fen);
779 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
780 const tc = extractTime(game.cadence);
781 const myIdx = game.players.findIndex(p => {
782 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
784 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
785 if (!game.chats) game.chats = []; //live games don't have chat history
786 if (gtype == "corr") {
787 if (game.players[0].color == "b") {
788 // Adopt the same convention for live and corr games: [0] = white
789 [game.players[0], game.players[1]] = [
794 // NOTE: clocks in seconds, initime in milliseconds
795 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
796 game.clocks = [tc.mainTime, tc.mainTime];
797 const L = game.moves.length;
798 if (game.score == "*") {
799 // Set clocks + initime
800 game.initime = [0, 0];
802 const gameLastupdate = game.moves[L-1].played;
803 game.initime[L % 2] = gameLastupdate;
806 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
810 // Sort chat messages from newest to oldest
811 game.chats.sort((c1, c2) => {
812 return c2.added - c1.added;
814 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
815 // Did a chat message arrive after my last move?
817 if (L == 1 && myIdx == 0)
818 dtLastMove = game.moves[0].played;
821 // It's now white turn
822 dtLastMove = game.moves[L-1-(1-myIdx)].played;
825 dtLastMove = game.moves[L-1-myIdx].played;
828 if (dtLastMove < game.chats[0].added)
829 document.getElementById("chatBtn").classList.add("somethingnew");
831 // Now that we used idx and played, re-format moves as for live games
832 game.moves = game.moves.map(m => m.squares);
834 if (gtype == "live" && game.clocks[0] < 0) {
836 game.clocks = [tc.mainTime, tc.mainTime];
837 if (game.score == "*") {
838 game.initime[0] = Date.now();
840 // I play in this live game; corr games don't have clocks+initime
841 GameStorage.update(game.id, {
843 initime: game.initime
848 if (!!game.drawOffer) {
849 if (game.drawOffer == "t")
851 this.drawOffer = "threerep";
853 // Draw offered by any of the players:
854 if (myIdx < 0) this.drawOffer = "received";
856 // I play in this game:
858 (game.drawOffer == "w" && myIdx == 0) ||
859 (game.drawOffer == "b" && myIdx == 1)
861 this.drawOffer = "sent";
862 else this.drawOffer = "received";
866 this.repeat = {}; //reset: scan past moves' FEN:
868 let vr_tmp = new V(game.fenStart);
870 game.moves.forEach(m => {
872 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
873 this.repeat[fenIdx] = this.repeat[fenIdx]
874 ? this.repeat[fenIdx] + 1
877 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
878 this.game = Object.assign(
879 // NOTE: assign mycolor here, since BaseGame could also be VS computer
882 increment: tc.increment,
884 // opponent sid not strictly required (or available), but easier
885 // at least oppsid or oppid is available anyway:
886 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
887 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
891 if (this.gameIsLoading)
892 // Re-load game because we missed some moves:
893 // artificially reset BaseGame (required if moves arrived in wrong order)
894 this.$refs["basegame"].re_setVariables();
897 this.gotMoveIdx = game.moves.length - 1;
898 // If we arrive here after 'nextGame' action, the board might be hidden
899 let boardDiv = document.querySelector(".game");
900 if (!!boardDiv && boardDiv.style.visibility == "hidden")
901 boardDiv.style.visibility = "visible";
904 this.$nextTick(() => {
905 this.game.rendered = true;
906 // Did lastate arrive before game was rendered?
907 if (this.lastate) this.processLastate();
909 if (this.gameIsLoading) {
910 this.gameIsLoading = false;
911 if (this.gotMoveIdx >= game.moves.length)
912 // Some moves arrived meanwhile...
915 if (!!callback) callback();
918 afterRetrieval(game);
921 if (this.gameRef.rid) {
922 // Remote live game: forgetting about callback func... (TODO: design)
923 this.send("askfullgame", { target: this.gameRef.rid });
925 // Local or corr game on server.
926 // NOTE: afterRetrieval() is never called if game not found
927 const gid = this.gameRef.id;
928 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
929 // corr games identifiers are integers
937 g.moves.forEach(m => {
938 m.squares = JSON.parse(m.squares);
947 GameStorage.get(this.gameRef.id, afterRetrieval);
950 re_setClocks: function() {
951 if (this.game.moves.length < 2 || this.game.score != "*") {
952 // 1st move not completed yet, or game over: freeze time
953 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
956 const currentTurn = this.vr.turn;
957 const currentMovesCount = this.game.moves.length;
958 const colorIdx = ["w", "b"].indexOf(currentTurn);
960 this.game.clocks[colorIdx] -
961 (Date.now() - this.game.initime[colorIdx]) / 1000;
962 this.virtualClocks = [0, 1].map(i => {
964 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
965 return ppt(this.game.clocks[i] - removeTime).split(':');
967 this.clockUpdate = setInterval(
971 this.game.moves.length > currentMovesCount ||
972 this.game.score != "*"
974 clearInterval(this.clockUpdate);
977 currentTurn == "w" ? "0-1" : "1-0",
984 ppt(Math.max(0, --countdown)).split(':')
990 // Update variables and storage after a move:
991 processMove: function(move, data) {
992 if (!data) data = {};
993 const moveCol = this.vr.turn;
994 const doProcessMove = () => {
995 const colorIdx = ["w", "b"].indexOf(moveCol);
996 const nextIdx = 1 - colorIdx;
997 const origMovescount = this.game.moves.length;
998 let addTime = 0; //for live games
999 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1000 if (this.drawOffer == "received")
1002 this.drawOffer = "";
1003 if (this.game.type == "live" && origMovescount >= 2) {
1004 const elapsed = Date.now() - this.game.initime[colorIdx];
1005 // elapsed time is measured in milliseconds
1006 addTime = this.game.increment - elapsed / 1000;
1009 // Update current game object:
1010 playMove(move, this.vr);
1011 // The move is played: stop clock
1012 clearInterval(this.clockUpdate);
1014 // Received move, score has not been computed in BaseGame (!!noemit)
1015 const score = this.vr.getCurrentScore();
1016 if (score != "*") this.gameOver(score);
1018 // TODO: notifyTurn: "changeturn" message
1019 this.game.moves.push(move);
1020 this.game.fen = this.vr.getFen();
1021 if (this.game.type == "live") {
1022 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
1023 else this.game.clocks[colorIdx] += addTime;
1025 // In corr games, just reset clock to mainTime:
1027 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1029 // NOTE: opponent's initime is reset after "gotmove" is received
1031 !this.game.mycolor ||
1032 moveCol != this.game.mycolor ||
1033 !!data.receiveMyMove
1035 this.game.initime[nextIdx] = Date.now();
1037 // If repetition detected, consider that a draw offer was received:
1038 const fenObj = this.vr.getFenForRepeat();
1039 this.repeat[fenObj] =
1040 !!this.repeat[fenObj]
1041 ? this.repeat[fenObj] + 1
1043 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1044 else if (this.drawOffer == "threerep") this.drawOffer = "";
1045 if (!!this.game.mycolor && !data.receiveMyMove) {
1046 // NOTE: 'var' to see that variable outside this block
1047 var filtered_move = getFilteredMove(move);
1049 // Since corr games are stored at only one location, update should be
1050 // done only by one player for each move:
1052 !!this.game.mycolor &&
1053 !data.receiveMyMove &&
1054 (this.game.type == "live" || moveCol == this.game.mycolor)
1057 switch (this.drawOffer) {
1062 drawCode = this.game.mycolor;
1065 drawCode = V.GetOppCol(this.game.mycolor);
1068 if (this.game.type == "corr") {
1069 // corr: only move, fen and score
1070 this.updateCorrGame({
1073 squares: filtered_move,
1077 // Code "n" for "None" to force reset (otherwise it's ignored)
1078 drawOffer: drawCode || "n"
1082 const updateStorage = () => {
1083 GameStorage.update(this.gameRef.id, {
1085 move: filtered_move,
1086 moveIdx: origMovescount,
1087 clocks: this.game.clocks,
1088 initime: this.game.initime,
1092 // The active tab can update storage immediately
1093 if (!document.hidden) updateStorage();
1094 // Small random delay otherwise
1095 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1098 // Send move ("newmove" event) to people in the room (if our turn)
1099 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1101 move: filtered_move,
1102 index: origMovescount,
1103 // color is required to check if this is my move (if several tabs opened)
1105 cancelDrawOffer: this.drawOffer == ""
1107 if (this.game.type == "live")
1108 sendMove["clock"] = this.game.clocks[colorIdx];
1109 this.opponentGotMove = false;
1110 this.send("newmove", {data: sendMove});
1111 // If the opponent doesn't reply gotmove soon enough, re-send move:
1112 // Do this at most 2 times, because mpore would mean network issues,
1113 // opponent would then be expected to disconnect/reconnect.
1115 const currentUrl = document.location.href;
1116 this.retrySendmove = setInterval(
1120 this.opponentGotMove ||
1121 document.location.href != currentUrl //page change
1123 clearInterval(this.retrySendmove);
1126 let oppsid = this.game.players[nextIdx].sid;
1128 oppsid = Object.keys(this.people).find(
1129 sid => this.people[sid].id == this.game.players[nextIdx].uid
1132 if (!oppsid || !this.people[oppsid])
1133 // Opponent is disconnected: he'll ask last state
1134 clearInterval(this.retrySendmove);
1136 this.send("newmove", { data: sendMove, target: oppsid });
1144 // Not my move or I'm an observer: just start other player's clock
1145 this.re_setClocks();
1148 this.game.type == "corr" &&
1149 moveCol == this.game.mycolor &&
1152 let boardDiv = document.querySelector(".game");
1153 const afterSetScore = () => {
1155 if (this.st.settings.gotonext && this.nextIds.length > 0)
1156 this.showNextGame();
1158 // The board might have been hidden:
1159 if (boardDiv.style.visibility == "hidden")
1160 boardDiv.style.visibility = "visible";
1163 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1164 // We may play several moves in a row: in case of, remove listener:
1165 let elClone = el.cloneNode(true);
1166 el.parentNode.replaceChild(elClone, el);
1167 elClone.addEventListener(
1170 document.getElementById("modalConfirm").checked = false;
1171 if (!!data.score && data.score != "*")
1173 this.gameOver(data.score, null, afterSetScore);
1174 else afterSetScore();
1177 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1178 V.PlayOnBoard(this.vr.board, move);
1179 const position = this.vr.getBaseFen();
1180 V.UndoOnBoard(this.vr.board, move);
1181 if (["all","byrow"].includes(V.ShowMoves)) {
1182 this.curDiag = getDiagram({
1184 orientation: V.CanFlip ? this.game.mycolor : "w"
1186 document.querySelector("#confirmDiv > .card").style.width =
1187 boardDiv.offsetWidth + "px";
1189 // Incomplete information: just ask confirmation
1190 // Hide the board, because otherwise it could reveal infos
1191 boardDiv.style.visibility = "hidden";
1192 this.moveNotation = getFullNotation(move);
1194 document.getElementById("modalConfirm").checked = true;
1198 if (!!data.score && data.score != "*")
1199 this.gameOver(data.score, null, doProcessMove);
1200 else doProcessMove();
1203 cancelMove: function() {
1204 let boardDiv = document.querySelector(".game");
1205 if (boardDiv.style.visibility == "hidden")
1206 boardDiv.style.visibility = "visible";
1207 document.getElementById("modalConfirm").checked = false;
1208 this.$refs["basegame"].cancelLastMove();
1210 // In corr games, callback to change page only after score is set:
1211 gameOver: function(score, scoreMsg, callback) {
1212 this.game.score = score;
1213 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1214 this.game.scoreMsg = scoreMsg;
1215 this.$set(this.game, "scoreMsg", scoreMsg);
1216 const myIdx = this.game.players.findIndex(p => {
1217 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1220 // OK, I play in this game
1225 if (this.game.type == "live") {
1226 GameStorage.update(this.gameRef.id, scoreObj);
1227 if (!!callback) callback();
1229 else this.updateCorrGame(scoreObj, callback);
1230 // Notify the score to main Hall. TODO: only one player (currently double send)
1231 this.send("result", { gid: this.game.id, score: score });
1233 else if (!!callback) callback();
1239 <style lang="sass" scoped>
1241 background-color: lightgreen
1253 @media screen and (min-width: 768px)
1256 @media screen and (max-width: 767px)
1261 display: inline-block
1265 display: inline-block
1267 display: inline-flex
1271 @media screen and (max-width: 767px)
1274 @media screen and (max-width: 767px)
1277 @media screen and (min-width: 768px)
1289 background-color: #edda99
1291 display: inline-block
1300 display: inline-block
1313 animation: blink-animation 2s steps(3, start) infinite
1314 @keyframes blink-animation
1319 display: inline-block
1331 .draw-sent, .draw-sent:hover
1332 background-color: lightyellow
1334 .draw-received, .draw-received:hover
1335 background-color: lightgreen
1337 .draw-threerep, .draw-threerep:hover
1338 background-color: #e4d1fc
1341 background-color: #c5fefe
1354 background-color: lightgreen
1356 background-color: red