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():
166 // Related to (killing of) self multi-connects:
172 $route: function(to, from) {
173 if (from.params["id"] != to.params["id"]) {
174 // Change everything:
175 this.cleanBeforeDestroy();
176 let boardDiv = document.querySelector(".game");
178 // In case of incomplete information variant:
179 boardDiv.style.visibility = "hidden";
183 this.gameRef.id = to.params["id"];
184 this.gameRef.rid = to.query["rid"];
185 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
190 // NOTE: some redundant code with Hall.vue (mostly related to people array)
191 created: function() {
194 mounted: function() {
196 .getElementById("chatWrap")
197 .addEventListener("click", processModalClick);
198 if ("ontouchstart" in window) {
199 // Disable tooltips on smartphones:
200 document.getElementsByClassName("tooltip").forEach(elt => {
201 elt.classList.remove("tooltip");
205 beforeDestroy: function() {
206 this.cleanBeforeDestroy();
209 atCreation: function() {
210 // 0] (Re)Set variables
211 this.gameRef.id = this.$route.params["id"];
212 // rid = remote ID to find an observed live game,
213 // next = next corr games IDs to navigate faster
214 // (Both might be undefined)
215 this.gameRef.rid = this.$route.query["rid"];
216 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
217 // Always add myself to players' list
218 const my = this.st.user;
219 this.$set(this.people, my.sid, { id: my.id, name: my.name });
221 players: [{ name: "" }, { name: "" }],
225 let chatComp = this.$refs["chatcomp"];
226 if (!!chatComp) chatComp.chats = [];
227 this.virtualClocks = [[0,0], [0,0]];
231 this.lastate = undefined;
233 this.roomInitialized = false;
234 this.askGameTime = 0;
235 this.gameIsLoading = false;
236 this.gotLastate = false;
237 this.gotMoveIdx = -1;
238 this.opponentGotMove = false;
239 this.askLastate = null;
240 this.retrySendmove = null;
241 this.clockUpdate = null;
242 this.newConnect = {};
244 // 1] Initialize connection
245 this.connexionString =
252 // Discard potential "/?next=[...]" for page indication:
253 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
254 this.conn = new WebSocket(this.connexionString);
255 this.conn.onmessage = this.socketMessageListener;
256 this.conn.onclose = this.socketCloseListener;
257 // Socket init required before loading remote game:
258 const socketInit = callback => {
259 if (!!this.conn && this.conn.readyState == 1)
263 // Socket not ready yet (initial loading)
264 // NOTE: it's important to call callback without arguments,
265 // otherwise first arg is Websocket object and loadGame fails.
266 this.conn.onopen = () => callback();
268 if (!this.gameRef.rid)
269 // Game stored locally or on server
270 this.loadGame(null, () => socketInit(this.roomInit));
272 // Game stored remotely: need socket to retrieve it
273 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
274 // --> It will be given when receiving "fullgame" socket event.
275 socketInit(this.loadGame);
277 cleanBeforeDestroy: function() {
278 if (!!this.askLastate)
279 clearInterval(this.askLastate);
280 if (!!this.retrySendmove)
281 clearInterval(this.retrySendmove);
282 if (!!this.clockUpdate)
283 clearInterval(this.clockUpdate);
284 this.send("disconnect");
286 roomInit: function() {
287 if (!this.roomInitialized) {
288 // Notify the room only now that I connected, because
289 // messages might be lost otherwise (if game loading is slow)
290 this.send("connect");
291 this.send("pollclients");
292 // We may ask fullgame several times if some moves are lost,
293 // but room should be init only once:
294 this.roomInitialized = true;
297 send: function(code, obj) {
299 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
301 isConnected: function(index) {
302 const player = this.game.players[index];
304 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
305 // Still have to check for name (because of potential multi-accounts
306 // on same browser, although this should be rare...)
307 return (!this.st.user.name || this.st.user.name == player.name);
308 // Try to find a match in people:
312 Object.keys(this.people).some(sid => sid == player.sid)
317 Object.values(this.people).some(p => p.id == player.uid)
321 resetChatColor: function() {
322 // TODO: this is called twice, once on opening an once on closing
323 document.getElementById("chatBtn").classList.remove("somethingnew");
325 processChat: function(chat) {
326 this.send("newchat", { data: chat });
327 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
328 if (this.game.type == "corr" && this.st.user.id > 0)
329 this.updateCorrGame({ chat: chat });
331 clearChat: function() {
332 // Nothing more to do if game is live (chats not recorded)
333 if (this.game.type == "corr") {
334 if (!!this.game.mycolor) {
338 { data: { 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 (document.location.href != currentUrl) 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 });
381 // Delay of at least 2s between two game requests
382 const now = Date.now();
383 const delay = Math.max(2000 - (now - this.askGameTime), 0);
384 this.askGameTime = now;
385 setTimeout(doAskGame, delay);
387 socketMessageListener: function(msg) {
388 if (!this.conn) return;
389 const data = JSON.parse(msg.data);
392 data.sockIds.forEach(sid => {
393 if (sid != this.st.user.sid)
394 this.send("askidentity", { target: sid });
398 if (!this.people[data.from]) {
399 this.newConnect[data.from] = true; //for self multi-connects tests
400 this.send("askidentity", { target: data.from });
404 this.$delete(this.people, data.from);
407 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
408 // Either me (another tab) or opponent
409 const sid = data.from;
410 if (!this.onMygames.some(s => s == sid))
412 this.onMygames.push(sid);
413 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
416 if (!this.people[sid])
417 this.send("askidentity", { target: sid });
420 ArrayFun.remove(this.onMygames, sid => sid == data.from);
423 // I logged in elsewhere:
425 alert(this.st.tr["New connexion detected: tab now offline"]);
427 case "askidentity": {
428 // Request for identification
430 // Decompose to avoid revealing email
431 name: this.st.user.name,
432 sid: this.st.user.sid,
435 this.send("identity", { data: me, target: data.from });
439 const user = data.data;
440 this.$set(this.people, user.sid, { name: user.name, id: user.id });
441 // If I multi-connect, kill current connexion if no mark (I'm older)
442 if (this.newConnect[user.sid]) {
445 user.id == this.st.user.id &&
446 user.sid != this.st.user.sid &&
447 !this.killed[this.st.user.sid]
449 this.send("killme", { sid: this.st.user.sid });
450 this.killed[this.st.user.sid] = true;
452 delete this.newConnect[user.sid];
454 if (!this.killed[this.st.user.sid]) {
455 // Ask potentially missed last state, if opponent and I play
457 !!this.game.mycolor &&
458 this.game.type == "live" &&
459 this.game.score == "*" &&
460 this.game.players.some(p => p.sid == user.sid)
462 this.send("asklastate", { target: user.sid });
464 this.askLastate = setInterval(
466 // Ask at most 3 times:
467 // if no reply after that there should be a network issue.
471 !!this.people[user.sid]
473 this.send("asklastate", { target: user.sid });
476 clearInterval(this.askLastate);
486 // Send current (live) game if not asked by any of the players
488 this.game.type == "live" &&
489 this.game.players.every(p => p.sid != data.from[0])
494 players: this.game.players,
496 cadence: this.game.cadence,
497 score: this.game.score,
498 rid: this.st.user.sid //useful in Hall if I'm an observer
500 this.send("game", { data: myGame, target: data.from });
504 const gameToSend = Object.keys(this.game)
507 "id","fen","players","vid","cadence","fenStart","vname",
508 "moves","clocks","initime","score","drawOffer"
512 obj[k] = this.game[k];
517 this.send("fullgame", { data: gameToSend, target: data.from });
520 // Callback "roomInit" to poll clients only after game is loaded
521 this.loadGame(data.data, this.roomInit);
524 // Sending informative last state if I played a move or score != "*"
526 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
527 this.game.score != "*" ||
528 this.drawOffer == "sent"
530 // Send our "last state" informations to opponent
531 const L = this.game.moves.length;
532 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
534 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
535 clock: this.game.clocks[myIdx],
536 // Since we played a move (or abort or resign),
537 // only drawOffer=="sent" is possible
538 drawSent: this.drawOffer == "sent",
539 score: this.game.score,
541 initime: this.game.initime[1 - myIdx] //relevant only if I played
543 this.send("lastate", { data: myLastate, target: data.from });
545 this.send("lastate", { data: {nothing: true}, target: data.from });
549 // Got opponent infos about last move
550 this.gotLastate = true;
551 if (!data.data.nothing) {
552 this.lastate = data.data;
553 if (this.game.rendered)
554 // Game is rendered (Board component)
555 this.processLastate();
556 // Else: will be processed when game is ready
561 const movePlus = data.data;
562 const movesCount = this.game.moves.length;
563 if (movePlus.index > movesCount) {
564 // This can only happen if I'm an observer and missed a move.
565 if (this.gotMoveIdx < movePlus.index)
566 this.gotMoveIdx = movePlus.index;
567 if (!this.gameIsLoading) this.askGameAgain();
571 movePlus.index < movesCount ||
572 this.gotMoveIdx >= movePlus.index
574 // Opponent re-send but we already have the move:
575 // (maybe he didn't receive our pingback...)
576 this.send("gotmove", {data: movePlus.index, target: data.from});
578 this.gotMoveIdx = movePlus.index;
579 const receiveMyMove = (movePlus.color == this.game.mycolor);
580 if (!receiveMyMove && !!this.game.mycolor)
581 // Notify opponent that I got the move:
582 this.send("gotmove", {data: movePlus.index, target: data.from});
583 if (movePlus.cancelDrawOffer) {
584 // Opponent refuses draw
586 // NOTE for corr games: drawOffer reset by player in turn
588 this.game.type == "live" &&
589 !!this.game.mycolor &&
592 GameStorage.update(this.gameRef.id, { drawOffer: "" });
595 this.$refs["basegame"].play(movePlus.move, "received", null, true);
599 clock: movePlus.clock,
600 receiveMyMove: receiveMyMove
608 this.opponentGotMove = true;
609 // Now his clock starts running:
610 const oppIdx = ['w','b'].indexOf(this.vr.turn);
611 this.game.initime[oppIdx] = Date.now();
616 const score = data.side == "b" ? "1-0" : "0-1";
617 const side = data.side == "w" ? "White" : "Black";
618 this.gameOver(score, side + " surrender");
621 this.gameOver("?", "Stop");
624 this.gameOver("1/2", data.data);
627 // NOTE: observers don't know who offered draw
628 this.drawOffer = "received";
631 this.newChat = data.data;
632 if (!document.getElementById("modalChat").checked)
633 document.getElementById("chatBtn").classList.add("somethingnew");
637 socketCloseListener: function() {
638 this.conn = new WebSocket(this.connexionString);
639 this.conn.addEventListener("message", this.socketMessageListener);
640 this.conn.addEventListener("close", this.socketCloseListener);
642 updateCorrGame: function(obj, callback) {
648 gid: this.gameRef.id,
652 if (!!callback) callback();
657 // lastate was received, but maybe game wasn't ready yet:
658 processLastate: function() {
659 const data = this.lastate;
660 this.lastate = undefined; //security...
661 const L = this.game.moves.length;
662 if (data.movesCount > L) {
663 // Just got last move from him
664 this.$refs["basegame"].play(data.lastMove, "received", null, true);
665 this.processMove(data.lastMove, { clock: data.clock });
667 if (data.drawSent) this.drawOffer = "received";
668 if (data.score != "*") {
670 if (this.game.score == "*")
671 // TODO: also pass scoreMsg in lastate
672 this.gameOver(data.score);
675 clickDraw: function() {
676 if (!this.game.mycolor) return; //I'm just spectator
677 if (["received", "threerep"].includes(this.drawOffer)) {
678 if (!confirm(this.st.tr["Accept draw?"])) return;
680 this.drawOffer == "received"
682 : "Three repetitions";
683 this.send("draw", { data: message });
684 this.gameOver("1/2", message);
685 } else if (this.drawOffer == "") {
686 // No effect if drawOffer == "sent"
687 if (this.game.mycolor != this.vr.turn) {
688 alert(this.st.tr["Draw offer only in your turn"]);
691 if (!confirm(this.st.tr["Offer draw?"])) return;
692 this.drawOffer = "sent";
693 this.send("drawoffer");
694 if (this.game.type == "live") {
697 { drawOffer: this.game.mycolor }
699 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
702 abortGame: function() {
703 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
704 this.gameOver("?", "Stop");
708 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
710 this.send("resign", { data: this.game.mycolor });
711 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
712 const side = this.game.mycolor == "w" ? "White" : "Black";
713 this.gameOver(score, side + " surrender");
715 // 3 cases for loading a game:
716 // - from indexedDB (running or completed live game I play)
717 // - from server (one correspondance game I play[ed] or not)
718 // - from remote peer (one live game I don't play, finished or not)
719 loadGame: function(game, callback) {
720 const afterRetrieval = async game => {
721 const vModule = await import("@/variants/" + game.vname + ".js");
722 window.V = vModule.VariantRules;
723 this.vr = new V(game.fen);
724 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
725 const tc = extractTime(game.cadence);
726 const myIdx = game.players.findIndex(p => {
727 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
729 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
730 if (!game.chats) game.chats = []; //live games don't have chat history
731 if (gtype == "corr") {
732 if (game.players[0].color == "b") {
733 // Adopt the same convention for live and corr games: [0] = white
734 [game.players[0], game.players[1]] = [
739 // NOTE: clocks in seconds, initime in milliseconds
740 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
741 game.clocks = [tc.mainTime, tc.mainTime];
742 const L = game.moves.length;
743 if (game.score == "*") {
744 // Set clocks + initime
745 game.initime = [0, 0];
747 const gameLastupdate = game.moves[L-1].played;
748 game.initime[L % 2] = gameLastupdate;
751 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
755 // Sort chat messages from newest to oldest
756 game.chats.sort((c1, c2) => {
757 return c2.added - c1.added;
759 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
760 // Did a chat message arrive after my last move?
762 if (L == 1 && myIdx == 0)
763 dtLastMove = game.moves[0].played;
766 // It's now white turn
767 dtLastMove = game.moves[L-1-(1-myIdx)].played;
770 dtLastMove = game.moves[L-1-myIdx].played;
773 if (dtLastMove < game.chats[0].added)
774 document.getElementById("chatBtn").classList.add("somethingnew");
776 // Now that we used idx and played, re-format moves as for live games
777 game.moves = game.moves.map(m => m.squares);
779 if (gtype == "live" && game.clocks[0] < 0) {
781 game.clocks = [tc.mainTime, tc.mainTime];
782 if (game.score == "*") {
783 game.initime[0] = Date.now();
785 // I play in this live game; corr games don't have clocks+initime
786 GameStorage.update(game.id, {
788 initime: game.initime
793 if (!!game.drawOffer) {
794 if (game.drawOffer == "t")
796 this.drawOffer = "threerep";
798 // Draw offered by any of the players:
799 if (myIdx < 0) this.drawOffer = "received";
801 // I play in this game:
803 (game.drawOffer == "w" && myIdx == 0) ||
804 (game.drawOffer == "b" && myIdx == 1)
806 this.drawOffer = "sent";
807 else this.drawOffer = "received";
811 this.repeat = {}; //reset: scan past moves' FEN:
813 let vr_tmp = new V(game.fenStart);
815 game.moves.forEach(m => {
817 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
818 this.repeat[fenIdx] = this.repeat[fenIdx]
819 ? this.repeat[fenIdx] + 1
822 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
823 this.game = Object.assign(
824 // NOTE: assign mycolor here, since BaseGame could also be VS computer
827 increment: tc.increment,
829 // opponent sid not strictly required (or available), but easier
830 // at least oppsid or oppid is available anyway:
831 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
832 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
836 if (this.gameIsLoading)
837 // Re-load game because we missed some moves:
838 // artificially reset BaseGame (required if moves arrived in wrong order)
839 this.$refs["basegame"].re_setVariables();
842 this.gotMoveIdx = game.moves.length - 1;
843 // If we arrive here after 'nextGame' action, the board might be hidden
844 let boardDiv = document.querySelector(".game");
845 if (!!boardDiv && boardDiv.style.visibility == "hidden")
846 boardDiv.style.visibility = "visible";
849 this.$nextTick(() => {
850 this.game.rendered = true;
851 // Did lastate arrive before game was rendered?
852 if (this.lastate) this.processLastate();
854 if (this.gameIsLoading) {
855 this.gameIsLoading = false;
856 if (this.gotMoveIdx >= game.moves.length)
857 // Some moves arrived meanwhile...
860 if (!!callback) callback();
863 afterRetrieval(game);
866 if (this.gameRef.rid) {
867 // Remote live game: forgetting about callback func... (TODO: design)
868 this.send("askfullgame", { target: this.gameRef.rid });
870 // Local or corr game on server.
871 // NOTE: afterRetrieval() is never called if game not found
872 const gid = this.gameRef.id;
873 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
874 // corr games identifiers are integers
882 g.moves.forEach(m => {
883 m.squares = JSON.parse(m.squares);
892 GameStorage.get(this.gameRef.id, afterRetrieval);
895 re_setClocks: function() {
896 if (this.game.moves.length < 2 || this.game.score != "*") {
897 // 1st move not completed yet, or game over: freeze time
898 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
901 const currentTurn = this.vr.turn;
902 const currentMovesCount = this.game.moves.length;
903 const colorIdx = ["w", "b"].indexOf(currentTurn);
905 this.game.clocks[colorIdx] -
906 (Date.now() - this.game.initime[colorIdx]) / 1000;
907 this.virtualClocks = [0, 1].map(i => {
909 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
910 return ppt(this.game.clocks[i] - removeTime).split(':');
912 this.clockUpdate = setInterval(
916 this.game.moves.length > currentMovesCount ||
917 this.game.score != "*"
919 clearInterval(this.clockUpdate);
922 currentTurn == "w" ? "0-1" : "1-0",
929 ppt(Math.max(0, --countdown)).split(':')
935 // Update variables and storage after a move:
936 processMove: function(move, data) {
937 if (!data) data = {};
938 const moveCol = this.vr.turn;
939 const doProcessMove = () => {
940 const colorIdx = ["w", "b"].indexOf(moveCol);
941 const nextIdx = 1 - colorIdx;
942 const origMovescount = this.game.moves.length;
943 let addTime = 0; //for live games
944 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
945 if (this.drawOffer == "received")
948 if (this.game.type == "live" && origMovescount >= 2) {
949 const elapsed = Date.now() - this.game.initime[colorIdx];
950 // elapsed time is measured in milliseconds
951 addTime = this.game.increment - elapsed / 1000;
954 // Update current game object:
955 playMove(move, this.vr);
956 // The move is played: stop clock
957 clearInterval(this.clockUpdate);
959 // Received move, score has not been computed in BaseGame (!!noemit)
960 const score = this.vr.getCurrentScore();
961 if (score != "*") this.gameOver(score);
963 // TODO: notifyTurn: "changeturn" message
964 this.game.moves.push(move);
965 this.game.fen = this.vr.getFen();
966 if (this.game.type == "live") {
967 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
968 else this.game.clocks[colorIdx] += addTime;
970 // In corr games, just reset clock to mainTime:
972 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
974 // NOTE: opponent's initime is reset after "gotmove" is received
976 !this.game.mycolor ||
977 moveCol != this.game.mycolor ||
980 this.game.initime[nextIdx] = Date.now();
982 // If repetition detected, consider that a draw offer was received:
983 const fenObj = this.vr.getFenForRepeat();
984 this.repeat[fenObj] =
985 !!this.repeat[fenObj]
986 ? this.repeat[fenObj] + 1
988 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
989 else if (this.drawOffer == "threerep") this.drawOffer = "";
990 if (!!this.game.mycolor && !data.receiveMyMove) {
991 // NOTE: 'var' to see that variable outside this block
992 var filtered_move = getFilteredMove(move);
994 // Since corr games are stored at only one location, update should be
995 // done only by one player for each move:
997 !!this.game.mycolor &&
998 !data.receiveMyMove &&
999 (this.game.type == "live" || moveCol == this.game.mycolor)
1002 switch (this.drawOffer) {
1007 drawCode = this.game.mycolor;
1010 drawCode = V.GetOppCol(this.game.mycolor);
1013 if (this.game.type == "corr") {
1014 // corr: only move, fen and score
1015 this.updateCorrGame({
1018 squares: filtered_move,
1022 // Code "n" for "None" to force reset (otherwise it's ignored)
1023 drawOffer: drawCode || "n"
1027 const updateStorage = () => {
1028 GameStorage.update(this.gameRef.id, {
1030 move: filtered_move,
1031 moveIdx: origMovescount,
1032 clocks: this.game.clocks,
1033 initime: this.game.initime,
1037 // The active tab can update storage immediately
1038 if (!document.hidden) updateStorage();
1039 // Small random delay otherwise
1040 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1043 // Send move ("newmove" event) to people in the room (if our turn)
1044 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1046 move: filtered_move,
1047 index: origMovescount,
1048 // color is required to check if this is my move (if several tabs opened)
1050 cancelDrawOffer: this.drawOffer == ""
1052 if (this.game.type == "live")
1053 sendMove["clock"] = this.game.clocks[colorIdx];
1054 this.opponentGotMove = false;
1055 this.send("newmove", {data: sendMove});
1056 // If the opponent doesn't reply gotmove soon enough, re-send move:
1057 // Do this at most 2 times, because mpore would mean network issues,
1058 // opponent would then be expected to disconnect/reconnect.
1060 const currentUrl = document.location.href;
1061 this.retrySendmove = setInterval(
1065 this.opponentGotMove ||
1066 document.location.href != currentUrl //page change
1068 clearInterval(this.retrySendmove);
1071 let oppsid = this.game.players[nextIdx].sid;
1073 oppsid = Object.keys(this.people).find(
1074 sid => this.people[sid].id == this.game.players[nextIdx].uid
1077 if (!oppsid || !this.people[oppsid])
1078 // Opponent is disconnected: he'll ask last state
1079 clearInterval(this.retrySendmove);
1081 this.send("newmove", { data: sendMove, target: oppsid });
1089 // Not my move or I'm an observer: just start other player's clock
1090 this.re_setClocks();
1093 this.game.type == "corr" &&
1094 moveCol == this.game.mycolor &&
1097 const afterSetScore = () => {
1099 if (this.st.settings.gotonext && this.nextIds.length > 0)
1100 this.showNextGame();
1102 // The board might have been hidden:
1103 let boardDiv = document.querySelector(".game");
1104 if (boardDiv.style.visibility == "hidden")
1105 boardDiv.style.visibility = "visible";
1108 if (["all","byrow"].includes(V.ShowMoves)) {
1109 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1110 // We may play several moves in a row: in case of, remove listener:
1111 let elClone = el.cloneNode(true);
1112 el.parentNode.replaceChild(elClone, el);
1113 elClone.addEventListener(
1116 document.getElementById("modalConfirm").checked = false;
1117 if (!!data.score && data.score != "*")
1119 this.gameOver(data.score, null, afterSetScore);
1120 else afterSetScore();
1123 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1124 V.PlayOnBoard(this.vr.board, move);
1125 const position = this.vr.getBaseFen();
1126 V.UndoOnBoard(this.vr.board, move);
1127 this.curDiag = getDiagram({
1129 orientation: V.CanFlip ? this.game.mycolor : "w"
1131 document.getElementById("modalConfirm").checked = true;
1133 // Incomplete information: just ask confirmation
1134 // Hide the board, because otherwise it could be revealed (TODO?)
1135 let boardDiv = document.querySelector(".game");
1136 boardDiv.style.visibility = "hidden";
1139 this.st.tr["Move played:"] + " " +
1140 getFullNotation(move) + "\n" +
1141 this.st.tr["Are you sure?"]
1144 this.$refs["basegame"].cancelLastMove();
1145 boardDiv.style.visibility = "visible";
1148 if (!!data.score && data.score != "*")
1149 this.gameOver(data.score, null, afterSetScore);
1150 else afterSetScore();
1155 if (!!data.score && data.score != "*")
1156 this.gameOver(data.score, null, doProcessMove);
1157 else doProcessMove();
1160 cancelMove: function() {
1161 document.getElementById("modalConfirm").checked = false;
1162 this.$refs["basegame"].cancelLastMove();
1164 // In corr games, callback to change page only after score is set:
1165 gameOver: function(score, scoreMsg, callback) {
1166 this.game.score = score;
1167 if (!scoreMsg) scoreMsg = getScoreMessage(score);
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