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")
34 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
38 span {{ st.tr["Move played:"] + " " }}
39 span.bold {{ moveNotation }}
41 span {{ st.tr["Are you sure?"] }}
42 .button-group#buttonsConfirm
43 // onClick for acceptBtn: set dynamically
45 span {{ st.tr["Validate"] }}
46 button.refuseBtn(@click="cancelMove()")
47 span {{ st.tr["Cancel"] }}
49 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
50 span.variant-cadence {{ game.cadence }}
51 span.variant-name {{ game.vname }}
53 v-if="nextIds.length > 0"
54 @click="showNextGame()"
56 | {{ st.tr["Next_g"] }}
57 button#chatBtn.tooltip(
58 onClick="window.doClick('modalChat')"
61 img(src="/images/icons/chat.svg")
62 #actions(v-if="game.score=='*'")
65 :class="{['draw-' + drawOffer]: true}"
66 :aria-label="st.tr['Draw']"
68 img(src="/images/icons/draw.svg")
72 :aria-label="st.tr['Abort']"
74 img(src="/images/icons/abort.svg")
78 :aria-label="st.tr['Resign']"
80 img(src="/images/icons/resign.svg")
82 v-else-if="!!game.mycolor"
84 :aria-label="st.tr['Rematch']"
86 img(src="/images/icons/rematch.svg")
89 span.name(:class="{connected: isConnected(0)}")
90 | {{ game.players[0].name || "@nonymous" }}
92 v-if="game.score=='*'"
93 :class="{yourturn: !!vr && vr.turn == 'w'}"
95 span.time-left {{ virtualClocks[0][0] }}
96 span.time-separator(v-if="!!virtualClocks[0][1]") :
97 span.time-right(v-if="!!virtualClocks[0][1]")
98 | {{ virtualClocks[0][1] }}
100 span.name(:class="{connected: isConnected(1)}")
101 | {{ game.players[1].name || "@nonymous" }}
103 v-if="game.score=='*'"
104 :class="{yourturn: !!vr && vr.turn == 'b'}"
106 span.time-left {{ virtualClocks[1][0] }}
107 span.time-separator(v-if="!!virtualClocks[1][1]") :
108 span.time-right(v-if="!!virtualClocks[1][1]")
109 | {{ virtualClocks[1][1] }}
113 @newmove="processMove"
118 import BaseGame from "@/components/BaseGame.vue";
119 import Chat from "@/components/Chat.vue";
120 import { store } from "@/store";
121 import { GameStorage } from "@/utils/gameStorage";
122 import { ppt } from "@/utils/datetime";
123 import { ajax } from "@/utils/ajax";
124 import { extractTime } from "@/utils/timeControl";
125 import { getRandString } from "@/utils/alea";
126 import { getScoreMessage } from "@/utils/scoring";
127 import { getFullNotation } from "@/utils/notation";
128 import { getDiagram } from "@/utils/printDiagram";
129 import { processModalClick } from "@/utils/modalClick";
130 import { playMove, getFilteredMove } from "@/utils/playUndo";
131 import { ArrayFun } from "@/utils/array";
132 import params from "@/parameters";
143 // rid = remote (socket) ID
148 game: {}, //passed to BaseGame
149 // virtualClocks will be initialized from true game.clocks
151 vr: null, //"variant rules" object initialized from FEN
153 people: {}, //players + observers
154 onMygames: [], //opponents (or me) on "MyGames" page
155 lastate: undefined, //used if opponent send lastate before game is ready
156 repeat: {}, //detect position repetition
157 curDiag: "", //for corr moves confirmation
160 roomInitialized: false,
161 // If newmove has wrong index: ask fullgame again:
163 gameIsLoading: false,
164 // If asklastate got no reply, ask again:
166 gotMoveIdx: -1, //last move index received
167 // If newmove got no pingback, send again:
168 opponentGotMove: false,
170 // Incomplete info games: show move played
172 // Intervals from setInterval():
176 // Related to (killing of) self multi-connects:
182 $route: function(to, from) {
183 if (from.params["id"] != to.params["id"]) {
184 // Change everything:
185 this.cleanBeforeDestroy();
186 let boardDiv = document.querySelector(".game");
188 // In case of incomplete information variant:
189 boardDiv.style.visibility = "hidden";
193 this.gameRef.id = to.params["id"];
194 this.gameRef.rid = to.query["rid"];
195 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
200 // NOTE: some redundant code with Hall.vue (mostly related to people array)
201 created: function() {
204 mounted: function() {
206 .getElementById("chatWrap")
207 .addEventListener("click", processModalClick);
208 if ("ontouchstart" in window) {
209 // Disable tooltips on smartphones:
210 document.getElementsByClassName("tooltip").forEach(elt => {
211 elt.classList.remove("tooltip");
215 beforeDestroy: function() {
216 this.cleanBeforeDestroy();
219 atCreation: function() {
220 // 0] (Re)Set variables
221 this.gameRef.id = this.$route.params["id"];
222 // rid = remote ID to find an observed live game,
223 // next = next corr games IDs to navigate faster
224 // (Both might be undefined)
225 this.gameRef.rid = this.$route.query["rid"];
226 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
227 // Always add myself to players' list
228 const my = this.st.user;
229 this.$set(this.people, my.sid, { id: my.id, name: my.name });
231 players: [{ name: "" }, { name: "" }],
235 let chatComp = this.$refs["chatcomp"];
236 if (!!chatComp) chatComp.chats = [];
237 this.virtualClocks = [[0,0], [0,0]];
241 this.lastate = undefined;
243 this.roomInitialized = false;
244 this.askGameTime = 0;
245 this.gameIsLoading = false;
246 this.gotLastate = false;
247 this.gotMoveIdx = -1;
248 this.opponentGotMove = false;
249 this.askLastate = null;
250 this.retrySendmove = null;
251 this.clockUpdate = null;
252 this.newConnect = {};
254 // 1] Initialize connection
255 this.connexionString =
262 // Discard potential "/?next=[...]" for page indication:
263 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
264 this.conn = new WebSocket(this.connexionString);
265 this.conn.onmessage = this.socketMessageListener;
266 this.conn.onclose = this.socketCloseListener;
267 // Socket init required before loading remote game:
268 const socketInit = callback => {
269 if (!!this.conn && this.conn.readyState == 1)
273 // Socket not ready yet (initial loading)
274 // NOTE: it's important to call callback without arguments,
275 // otherwise first arg is Websocket object and loadGame fails.
276 this.conn.onopen = () => callback();
278 if (!this.gameRef.rid)
279 // Game stored locally or on server
280 this.loadGame(null, () => socketInit(this.roomInit));
282 // Game stored remotely: need socket to retrieve it
283 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
284 // --> It will be given when receiving "fullgame" socket event.
285 socketInit(this.loadGame);
287 cleanBeforeDestroy: function() {
288 if (!!this.askLastate)
289 clearInterval(this.askLastate);
290 if (!!this.retrySendmove)
291 clearInterval(this.retrySendmove);
292 if (!!this.clockUpdate)
293 clearInterval(this.clockUpdate);
294 this.send("disconnect");
296 roomInit: function() {
297 if (!this.roomInitialized) {
298 // Notify the room only now that I connected, because
299 // messages might be lost otherwise (if game loading is slow)
300 this.send("connect");
301 this.send("pollclients");
302 // We may ask fullgame several times if some moves are lost,
303 // but room should be init only once:
304 this.roomInitialized = true;
307 send: function(code, obj) {
309 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
311 isConnected: function(index) {
312 const player = this.game.players[index];
314 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
315 // Still have to check for name (because of potential multi-accounts
316 // on same browser, although this should be rare...)
317 return (!this.st.user.name || this.st.user.name == player.name);
318 // Try to find a match in people:
322 Object.keys(this.people).some(sid => sid == player.sid)
327 Object.values(this.people).some(p => p.id == player.uid)
331 resetChatColor: function() {
332 // TODO: this is called twice, once on opening an once on closing
333 document.getElementById("chatBtn").classList.remove("somethingnew");
335 processChat: function(chat) {
336 this.send("newchat", { data: chat });
337 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
338 if (this.game.type == "corr" && this.st.user.id > 0)
339 this.updateCorrGame({ chat: chat });
341 clearChat: function() {
342 // Nothing more to do if game is live (chats not recorded)
343 if (this.game.type == "corr") {
344 if (!!this.game.mycolor) {
348 { data: { gid: this.game.id } }
351 this.$set(this.game, "chats", []);
354 // Notify turn after a new move (to opponent and me on MyGames page)
355 notifyTurn: function(sid) {
356 const player = this.people[sid];
357 const colorIdx = this.game.players.findIndex(
358 p => p.sid == sid || p.uid == player.id);
359 const color = ["w","b"][colorIdx];
360 const movesCount = this.game.moves.length;
362 (color == "w" && movesCount % 2 == 0) ||
363 (color == "b" && movesCount % 2 == 1);
364 this.send("turnchange", { target: sid, yourTurn: yourTurn });
366 showNextGame: function() {
367 // Did I play in current game? If not, add it to nextIds list
368 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
369 this.nextIds.unshift(this.game.id);
370 const nextGid = this.nextIds.pop();
372 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
374 rematch: function() {
375 alert("Unimplemented yet (soon :) )");
376 // TODO: same logic as for draw, but re-click remove rematch offer (toggle)
378 askGameAgain: function() {
379 this.gameIsLoading = true;
380 const currentUrl = document.location.href;
381 const doAskGame = () => {
382 if (document.location.href != currentUrl) return; //page change
383 if (!this.gameRef.rid)
384 // This is my game: just reload.
387 // Just ask fullgame again (once!), this is much simpler.
388 // If this fails, the user could just reload page :/
389 this.send("askfullgame", { target: this.gameRef.rid });
391 // Delay of at least 2s between two game requests
392 const now = Date.now();
393 const delay = Math.max(2000 - (now - this.askGameTime), 0);
394 this.askGameTime = now;
395 setTimeout(doAskGame, delay);
397 socketMessageListener: function(msg) {
398 if (!this.conn) return;
399 const data = JSON.parse(msg.data);
402 data.sockIds.forEach(sid => {
403 if (sid != this.st.user.sid)
404 this.send("askidentity", { target: sid });
408 if (!this.people[data.from]) {
409 this.newConnect[data.from] = true; //for self multi-connects tests
410 this.send("askidentity", { target: data.from });
414 this.$delete(this.people, data.from);
417 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
418 // Either me (another tab) or opponent
419 const sid = data.from;
420 if (!this.onMygames.some(s => s == sid))
422 this.onMygames.push(sid);
423 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
426 if (!this.people[sid])
427 this.send("askidentity", { target: sid });
430 ArrayFun.remove(this.onMygames, sid => sid == data.from);
433 // I logged in elsewhere:
435 alert(this.st.tr["New connexion detected: tab now offline"]);
437 case "askidentity": {
438 // Request for identification
440 // Decompose to avoid revealing email
441 name: this.st.user.name,
442 sid: this.st.user.sid,
445 this.send("identity", { data: me, target: data.from });
449 const user = data.data;
450 this.$set(this.people, user.sid, { name: user.name, id: user.id });
451 // If I multi-connect, kill current connexion if no mark (I'm older)
452 if (this.newConnect[user.sid]) {
455 user.id == this.st.user.id &&
456 user.sid != this.st.user.sid &&
457 !this.killed[this.st.user.sid]
459 this.send("killme", { sid: this.st.user.sid });
460 this.killed[this.st.user.sid] = true;
462 delete this.newConnect[user.sid];
464 if (!this.killed[this.st.user.sid]) {
465 // Ask potentially missed last state, if opponent and I play
467 !!this.game.mycolor &&
468 this.game.type == "live" &&
469 this.game.score == "*" &&
470 this.game.players.some(p => p.sid == user.sid)
472 this.send("asklastate", { target: user.sid });
474 this.askLastate = setInterval(
476 // Ask at most 3 times:
477 // if no reply after that there should be a network issue.
481 !!this.people[user.sid]
483 this.send("asklastate", { target: user.sid });
486 clearInterval(this.askLastate);
496 // Send current (live) game if not asked by any of the players
498 this.game.type == "live" &&
499 this.game.players.every(p => p.sid != data.from[0])
504 players: this.game.players,
506 cadence: this.game.cadence,
507 score: this.game.score,
508 rid: this.st.user.sid //useful in Hall if I'm an observer
510 this.send("game", { data: myGame, target: data.from });
514 const gameToSend = Object.keys(this.game)
517 "id","fen","players","vid","cadence","fenStart","vname",
518 "moves","clocks","initime","score","drawOffer"
522 obj[k] = this.game[k];
527 this.send("fullgame", { data: gameToSend, target: data.from });
530 // Callback "roomInit" to poll clients only after game is loaded
531 this.loadGame(data.data, this.roomInit);
534 // Sending informative last state if I played a move or score != "*"
536 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
537 this.game.score != "*" ||
538 this.drawOffer == "sent"
540 // Send our "last state" informations to opponent
541 const L = this.game.moves.length;
542 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
544 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
545 clock: this.game.clocks[myIdx],
546 // Since we played a move (or abort or resign),
547 // only drawOffer=="sent" is possible
548 drawSent: this.drawOffer == "sent",
549 score: this.game.score,
550 score: this.game.scoreMsg,
552 initime: this.game.initime[1 - myIdx] //relevant only if I played
554 this.send("lastate", { data: myLastate, target: data.from });
556 this.send("lastate", { data: {nothing: true}, target: data.from });
560 // Got opponent infos about last move
561 this.gotLastate = true;
562 if (!data.data.nothing) {
563 this.lastate = data.data;
564 if (this.game.rendered)
565 // Game is rendered (Board component)
566 this.processLastate();
567 // Else: will be processed when game is ready
572 const movePlus = data.data;
573 const movesCount = this.game.moves.length;
574 if (movePlus.index > movesCount) {
575 // This can only happen if I'm an observer and missed a move.
576 if (this.gotMoveIdx < movePlus.index)
577 this.gotMoveIdx = movePlus.index;
578 if (!this.gameIsLoading) this.askGameAgain();
582 movePlus.index < movesCount ||
583 this.gotMoveIdx >= movePlus.index
585 // Opponent re-send but we already have the move:
586 // (maybe he didn't receive our pingback...)
587 this.send("gotmove", {data: movePlus.index, target: data.from});
589 this.gotMoveIdx = movePlus.index;
590 const receiveMyMove = (movePlus.color == this.game.mycolor);
591 if (!receiveMyMove && !!this.game.mycolor)
592 // Notify opponent that I got the move:
593 this.send("gotmove", {data: movePlus.index, target: data.from});
594 if (movePlus.cancelDrawOffer) {
595 // Opponent refuses draw
597 // NOTE for corr games: drawOffer reset by player in turn
599 this.game.type == "live" &&
600 !!this.game.mycolor &&
603 GameStorage.update(this.gameRef.id, { drawOffer: "" });
606 this.$refs["basegame"].play(movePlus.move, "received", null, true);
610 clock: movePlus.clock,
611 receiveMyMove: receiveMyMove
619 this.opponentGotMove = true;
620 // Now his clock starts running:
621 const oppIdx = ['w','b'].indexOf(this.vr.turn);
622 this.game.initime[oppIdx] = Date.now();
627 const score = data.side == "b" ? "1-0" : "0-1";
628 const side = data.side == "w" ? "White" : "Black";
629 this.gameOver(score, side + " surrender");
632 this.gameOver("?", "Stop");
635 this.gameOver("1/2", data.data);
638 // NOTE: observers don't know who offered draw
639 this.drawOffer = "received";
642 this.newChat = data.data;
643 if (!document.getElementById("modalChat").checked)
644 document.getElementById("chatBtn").classList.add("somethingnew");
648 socketCloseListener: function() {
649 this.conn = new WebSocket(this.connexionString);
650 this.conn.addEventListener("message", this.socketMessageListener);
651 this.conn.addEventListener("close", this.socketCloseListener);
653 updateCorrGame: function(obj, callback) {
659 gid: this.gameRef.id,
663 if (!!callback) callback();
668 // lastate was received, but maybe game wasn't ready yet:
669 processLastate: function() {
670 const data = this.lastate;
671 this.lastate = undefined; //security...
672 const L = this.game.moves.length;
673 if (data.movesCount > L) {
674 // Just got last move from him
675 this.$refs["basegame"].play(data.lastMove, "received", null, true);
676 this.processMove(data.lastMove, { clock: data.clock });
678 if (data.drawSent) this.drawOffer = "received";
679 if (data.score != "*") {
681 if (this.game.score == "*")
682 this.gameOver(data.score, data.scoreMsg);
685 clickDraw: function() {
686 if (!this.game.mycolor) return; //I'm just spectator
687 if (["received", "threerep"].includes(this.drawOffer)) {
688 if (!confirm(this.st.tr["Accept draw?"])) return;
690 this.drawOffer == "received"
692 : "Three repetitions";
693 this.send("draw", { data: message });
694 this.gameOver("1/2", message);
695 } else if (this.drawOffer == "") {
696 // No effect if drawOffer == "sent"
697 if (this.game.mycolor != this.vr.turn) {
698 alert(this.st.tr["Draw offer only in your turn"]);
701 if (!confirm(this.st.tr["Offer draw?"])) return;
702 this.drawOffer = "sent";
703 this.send("drawoffer");
704 if (this.game.type == "live") {
707 { drawOffer: this.game.mycolor }
709 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
712 abortGame: function() {
713 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
714 this.gameOver("?", "Stop");
718 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
720 this.send("resign", { data: this.game.mycolor });
721 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
722 const side = this.game.mycolor == "w" ? "White" : "Black";
723 this.gameOver(score, side + " surrender");
725 // 3 cases for loading a game:
726 // - from indexedDB (running or completed live game I play)
727 // - from server (one correspondance game I play[ed] or not)
728 // - from remote peer (one live game I don't play, finished or not)
729 loadGame: function(game, callback) {
730 const afterRetrieval = async game => {
731 const vModule = await import("@/variants/" + game.vname + ".js");
732 window.V = vModule.VariantRules;
733 this.vr = new V(game.fen);
734 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
735 const tc = extractTime(game.cadence);
736 const myIdx = game.players.findIndex(p => {
737 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
739 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
740 if (!game.chats) game.chats = []; //live games don't have chat history
741 if (gtype == "corr") {
742 if (game.players[0].color == "b") {
743 // Adopt the same convention for live and corr games: [0] = white
744 [game.players[0], game.players[1]] = [
749 // NOTE: clocks in seconds, initime in milliseconds
750 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
751 game.clocks = [tc.mainTime, tc.mainTime];
752 const L = game.moves.length;
753 if (game.score == "*") {
754 // Set clocks + initime
755 game.initime = [0, 0];
757 const gameLastupdate = game.moves[L-1].played;
758 game.initime[L % 2] = gameLastupdate;
761 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
765 // Sort chat messages from newest to oldest
766 game.chats.sort((c1, c2) => {
767 return c2.added - c1.added;
769 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
770 // Did a chat message arrive after my last move?
772 if (L == 1 && myIdx == 0)
773 dtLastMove = game.moves[0].played;
776 // It's now white turn
777 dtLastMove = game.moves[L-1-(1-myIdx)].played;
780 dtLastMove = game.moves[L-1-myIdx].played;
783 if (dtLastMove < game.chats[0].added)
784 document.getElementById("chatBtn").classList.add("somethingnew");
786 // Now that we used idx and played, re-format moves as for live games
787 game.moves = game.moves.map(m => m.squares);
789 if (gtype == "live" && game.clocks[0] < 0) {
791 game.clocks = [tc.mainTime, tc.mainTime];
792 if (game.score == "*") {
793 game.initime[0] = Date.now();
795 // I play in this live game; corr games don't have clocks+initime
796 GameStorage.update(game.id, {
798 initime: game.initime
803 if (!!game.drawOffer) {
804 if (game.drawOffer == "t")
806 this.drawOffer = "threerep";
808 // Draw offered by any of the players:
809 if (myIdx < 0) this.drawOffer = "received";
811 // I play in this game:
813 (game.drawOffer == "w" && myIdx == 0) ||
814 (game.drawOffer == "b" && myIdx == 1)
816 this.drawOffer = "sent";
817 else this.drawOffer = "received";
821 this.repeat = {}; //reset: scan past moves' FEN:
823 let vr_tmp = new V(game.fenStart);
825 game.moves.forEach(m => {
827 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
828 this.repeat[fenIdx] = this.repeat[fenIdx]
829 ? this.repeat[fenIdx] + 1
832 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
833 this.game = Object.assign(
834 // NOTE: assign mycolor here, since BaseGame could also be VS computer
837 increment: tc.increment,
839 // opponent sid not strictly required (or available), but easier
840 // at least oppsid or oppid is available anyway:
841 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
842 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
846 if (this.gameIsLoading)
847 // Re-load game because we missed some moves:
848 // artificially reset BaseGame (required if moves arrived in wrong order)
849 this.$refs["basegame"].re_setVariables();
852 this.gotMoveIdx = game.moves.length - 1;
853 // If we arrive here after 'nextGame' action, the board might be hidden
854 let boardDiv = document.querySelector(".game");
855 if (!!boardDiv && boardDiv.style.visibility == "hidden")
856 boardDiv.style.visibility = "visible";
859 this.$nextTick(() => {
860 this.game.rendered = true;
861 // Did lastate arrive before game was rendered?
862 if (this.lastate) this.processLastate();
864 if (this.gameIsLoading) {
865 this.gameIsLoading = false;
866 if (this.gotMoveIdx >= game.moves.length)
867 // Some moves arrived meanwhile...
870 if (!!callback) callback();
873 afterRetrieval(game);
876 if (this.gameRef.rid) {
877 // Remote live game: forgetting about callback func... (TODO: design)
878 this.send("askfullgame", { target: this.gameRef.rid });
880 // Local or corr game on server.
881 // NOTE: afterRetrieval() is never called if game not found
882 const gid = this.gameRef.id;
883 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
884 // corr games identifiers are integers
892 g.moves.forEach(m => {
893 m.squares = JSON.parse(m.squares);
902 GameStorage.get(this.gameRef.id, afterRetrieval);
905 re_setClocks: function() {
906 if (this.game.moves.length < 2 || this.game.score != "*") {
907 // 1st move not completed yet, or game over: freeze time
908 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
911 const currentTurn = this.vr.turn;
912 const currentMovesCount = this.game.moves.length;
913 const colorIdx = ["w", "b"].indexOf(currentTurn);
915 this.game.clocks[colorIdx] -
916 (Date.now() - this.game.initime[colorIdx]) / 1000;
917 this.virtualClocks = [0, 1].map(i => {
919 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
920 return ppt(this.game.clocks[i] - removeTime).split(':');
922 this.clockUpdate = setInterval(
926 this.game.moves.length > currentMovesCount ||
927 this.game.score != "*"
929 clearInterval(this.clockUpdate);
932 currentTurn == "w" ? "0-1" : "1-0",
939 ppt(Math.max(0, --countdown)).split(':')
945 // Update variables and storage after a move:
946 processMove: function(move, data) {
947 if (!data) data = {};
948 const moveCol = this.vr.turn;
949 const doProcessMove = () => {
950 const colorIdx = ["w", "b"].indexOf(moveCol);
951 const nextIdx = 1 - colorIdx;
952 const origMovescount = this.game.moves.length;
953 let addTime = 0; //for live games
954 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
955 if (this.drawOffer == "received")
958 if (this.game.type == "live" && origMovescount >= 2) {
959 const elapsed = Date.now() - this.game.initime[colorIdx];
960 // elapsed time is measured in milliseconds
961 addTime = this.game.increment - elapsed / 1000;
964 // Update current game object:
965 playMove(move, this.vr);
966 // The move is played: stop clock
967 clearInterval(this.clockUpdate);
969 // Received move, score has not been computed in BaseGame (!!noemit)
970 const score = this.vr.getCurrentScore();
971 if (score != "*") this.gameOver(score);
973 // TODO: notifyTurn: "changeturn" message
974 this.game.moves.push(move);
975 this.game.fen = this.vr.getFen();
976 if (this.game.type == "live") {
977 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
978 else this.game.clocks[colorIdx] += addTime;
980 // In corr games, just reset clock to mainTime:
982 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
984 // NOTE: opponent's initime is reset after "gotmove" is received
986 !this.game.mycolor ||
987 moveCol != this.game.mycolor ||
990 this.game.initime[nextIdx] = Date.now();
992 // If repetition detected, consider that a draw offer was received:
993 const fenObj = this.vr.getFenForRepeat();
994 this.repeat[fenObj] =
995 !!this.repeat[fenObj]
996 ? this.repeat[fenObj] + 1
998 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
999 else if (this.drawOffer == "threerep") this.drawOffer = "";
1000 if (!!this.game.mycolor && !data.receiveMyMove) {
1001 // NOTE: 'var' to see that variable outside this block
1002 var filtered_move = getFilteredMove(move);
1004 // Since corr games are stored at only one location, update should be
1005 // done only by one player for each move:
1007 !!this.game.mycolor &&
1008 !data.receiveMyMove &&
1009 (this.game.type == "live" || moveCol == this.game.mycolor)
1012 switch (this.drawOffer) {
1017 drawCode = this.game.mycolor;
1020 drawCode = V.GetOppCol(this.game.mycolor);
1023 if (this.game.type == "corr") {
1024 // corr: only move, fen and score
1025 this.updateCorrGame({
1028 squares: filtered_move,
1032 // Code "n" for "None" to force reset (otherwise it's ignored)
1033 drawOffer: drawCode || "n"
1037 const updateStorage = () => {
1038 GameStorage.update(this.gameRef.id, {
1040 move: filtered_move,
1041 moveIdx: origMovescount,
1042 clocks: this.game.clocks,
1043 initime: this.game.initime,
1047 // The active tab can update storage immediately
1048 if (!document.hidden) updateStorage();
1049 // Small random delay otherwise
1050 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1053 // Send move ("newmove" event) to people in the room (if our turn)
1054 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1056 move: filtered_move,
1057 index: origMovescount,
1058 // color is required to check if this is my move (if several tabs opened)
1060 cancelDrawOffer: this.drawOffer == ""
1062 if (this.game.type == "live")
1063 sendMove["clock"] = this.game.clocks[colorIdx];
1064 this.opponentGotMove = false;
1065 this.send("newmove", {data: sendMove});
1066 // If the opponent doesn't reply gotmove soon enough, re-send move:
1067 // Do this at most 2 times, because mpore would mean network issues,
1068 // opponent would then be expected to disconnect/reconnect.
1070 const currentUrl = document.location.href;
1071 this.retrySendmove = setInterval(
1075 this.opponentGotMove ||
1076 document.location.href != currentUrl //page change
1078 clearInterval(this.retrySendmove);
1081 let oppsid = this.game.players[nextIdx].sid;
1083 oppsid = Object.keys(this.people).find(
1084 sid => this.people[sid].id == this.game.players[nextIdx].uid
1087 if (!oppsid || !this.people[oppsid])
1088 // Opponent is disconnected: he'll ask last state
1089 clearInterval(this.retrySendmove);
1091 this.send("newmove", { data: sendMove, target: oppsid });
1099 // Not my move or I'm an observer: just start other player's clock
1100 this.re_setClocks();
1103 this.game.type == "corr" &&
1104 moveCol == this.game.mycolor &&
1107 let boardDiv = document.querySelector(".game");
1108 const afterSetScore = () => {
1110 if (this.st.settings.gotonext && this.nextIds.length > 0)
1111 this.showNextGame();
1113 // The board might have been hidden:
1114 if (boardDiv.style.visibility == "hidden")
1115 boardDiv.style.visibility = "visible";
1118 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1119 // We may play several moves in a row: in case of, remove listener:
1120 let elClone = el.cloneNode(true);
1121 el.parentNode.replaceChild(elClone, el);
1122 elClone.addEventListener(
1125 document.getElementById("modalConfirm").checked = false;
1126 if (!!data.score && data.score != "*")
1128 this.gameOver(data.score, null, afterSetScore);
1129 else afterSetScore();
1132 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1133 V.PlayOnBoard(this.vr.board, move);
1134 const position = this.vr.getBaseFen();
1135 V.UndoOnBoard(this.vr.board, move);
1136 if (["all","byrow"].includes(V.ShowMoves)) {
1137 this.curDiag = getDiagram({
1139 orientation: V.CanFlip ? this.game.mycolor : "w"
1142 // Incomplete information: just ask confirmation
1143 // Hide the board, because otherwise it could reveal infos
1144 boardDiv.style.visibility = "hidden";
1145 this.moveNotation = getFullNotation(move);
1147 document.getElementById("modalConfirm").checked = true;
1151 if (!!data.score && data.score != "*")
1152 this.gameOver(data.score, null, doProcessMove);
1153 else doProcessMove();
1156 cancelMove: function() {
1157 let boardDiv = document.querySelector(".game");
1158 if (boardDiv.style.visibility == "hidden")
1159 boardDiv.style.visibility = "visible";
1160 document.getElementById("modalConfirm").checked = false;
1161 this.$refs["basegame"].cancelLastMove();
1163 // In corr games, callback to change page only after score is set:
1164 gameOver: function(score, scoreMsg, callback) {
1165 this.game.score = score;
1166 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1167 this.game.scoreMsg = scoreMsg;
1168 this.$set(this.game, "scoreMsg", scoreMsg);
1169 const myIdx = this.game.players.findIndex(p => {
1170 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1173 // OK, I play in this game
1178 if (this.game.type == "live") {
1179 GameStorage.update(this.gameRef.id, scoreObj);
1180 if (!!callback) callback();
1182 else this.updateCorrGame(scoreObj, callback);
1183 // Notify the score to main Hall. TODO: only one player (currently double send)
1184 this.send("result", { gid: this.game.id, score: score });
1186 else if (!!callback) callback();
1192 <style lang="sass" scoped>
1194 background-color: lightgreen
1206 @media screen and (min-width: 768px)
1209 @media screen and (max-width: 767px)
1214 display: inline-block
1218 display: inline-block
1220 display: inline-flex
1224 @media screen and (max-width: 767px)
1227 @media screen and (max-width: 767px)
1230 @media screen and (min-width: 768px)
1242 background-color: #edda99
1244 display: inline-block
1253 display: inline-block
1266 animation: blink-animation 2s steps(3, start) infinite
1267 @keyframes blink-animation
1272 display: inline-block
1284 .draw-sent, .draw-sent:hover
1285 background-color: lightyellow
1287 .draw-received, .draw-received:hover
1288 background-color: lightgreen
1290 .draw-threerep, .draw-threerep:hover
1291 background-color: #e4d1fc
1294 background-color: #c5fefe
1299 // width: 100% required for Firefox
1309 background-color: lightgreen
1311 background-color: red