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"
111 import BaseGame from "@/components/BaseGame.vue";
112 import Chat from "@/components/Chat.vue";
113 import { store } from "@/store";
114 import { GameStorage } from "@/utils/gameStorage";
115 import { ppt } from "@/utils/datetime";
116 import { ajax } from "@/utils/ajax";
117 import { extractTime } from "@/utils/timeControl";
118 import { getRandString } from "@/utils/alea";
119 import { getDiagram } from "@/utils/printDiagram";
120 import { processModalClick } from "@/utils/modalClick";
121 import { playMove, getFilteredMove } from "@/utils/playUndo";
122 import { getScoreMessage } from "@/utils/scoring";
123 import { ArrayFun } from "@/utils/array";
124 import params from "@/parameters";
135 // rid = remote (socket) ID
140 game: {}, //passed to BaseGame
141 // virtualClocks will be initialized from true game.clocks
143 vr: null, //"variant rules" object initialized from FEN
145 people: {}, //players + observers
146 onMygames: [], //opponents (or me) on "MyGames" page
147 lastate: undefined, //used if opponent send lastate before game is ready
148 repeat: {}, //detect position repetition
149 curDiag: "", //for corr moves confirmation
152 roomInitialized: false,
153 // If newmove has wrong index: ask fullgame again:
155 gameIsLoading: false,
156 // If asklastate got no reply, ask again:
158 gotMoveIdx: -1, //last move index received
159 // If newmove got no pingback, send again:
160 opponentGotMove: false,
162 // Intervals from setInterval():
163 // TODO: limit them to e.g. 3 retries ?!
164 askIfPeerConnected: null,
168 // Related to (killing of) self multi-connects:
174 $route: function(to, from) {
175 if (from.params["id"] != to.params["id"]) {
176 // Change everything:
177 this.cleanBeforeDestroy();
181 this.gameRef.id = to.params["id"];
182 this.gameRef.rid = to.query["rid"];
183 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
188 // NOTE: some redundant code with Hall.vue (mostly related to people array)
189 created: function() {
192 mounted: function() {
194 .getElementById("chatWrap")
195 .addEventListener("click", processModalClick);
196 if ("ontouchstart" in window) {
197 // Disable tooltips on smartphones:
198 document.getElementsByClassName("tooltip").forEach(elt => {
199 elt.classList.remove("tooltip");
203 beforeDestroy: function() {
204 this.cleanBeforeDestroy();
207 atCreation: function() {
208 // 0] (Re)Set variables
209 this.gameRef.id = this.$route.params["id"];
210 // rid = remote ID to find an observed live game,
211 // next = next corr games IDs to navigate faster
212 // (Both might be undefined)
213 this.gameRef.rid = this.$route.query["rid"];
214 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
215 // Always add myself to players' list
216 const my = this.st.user;
217 this.$set(this.people, my.sid, { id: my.id, name: my.name });
219 players: [{ name: "" }, { name: "" }],
223 let chatComp = this.$refs["chatcomp"];
224 if (!!chatComp) chatComp.chats = [];
225 this.virtualClocks = [[0,0], [0,0]];
229 this.lastate = undefined;
231 this.roomInitialized = false;
232 this.askGameTime = 0;
233 this.gameIsLoading = false;
234 this.gotLastate = false;
235 this.gotMoveIdx = -1;
236 this.opponentGotMove = false;
237 this.askIfPeerConnected = null;
238 this.askLastate = null;
239 this.retrySendmove = null;
240 this.clockUpdate = null;
241 this.newConnect = {};
243 // 1] Initialize connection
244 this.connexionString =
251 // Discard potential "/?next=[...]" for page indication:
252 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
253 this.conn = new WebSocket(this.connexionString);
254 this.conn.onmessage = this.socketMessageListener;
255 this.conn.onclose = this.socketCloseListener;
256 // Socket init required before loading remote game:
257 const socketInit = callback => {
258 if (!!this.conn && this.conn.readyState == 1)
262 // Socket not ready yet (initial loading)
263 // NOTE: it's important to call callback without arguments,
264 // otherwise first arg is Websocket object and loadGame fails.
265 this.conn.onopen = () => callback();
267 if (!this.gameRef.rid)
268 // Game stored locally or on server
269 this.loadGame(null, () => socketInit(this.roomInit));
271 // Game stored remotely: need socket to retrieve it
272 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
273 // --> It will be given when receiving "fullgame" socket event.
274 socketInit(this.loadGame);
276 cleanBeforeDestroy: function() {
277 if (!!this.askIfPeerConnected)
278 clearInterval(this.askIfPeerConnected);
279 if (!!this.askLastate)
280 clearInterval(this.askLastate);
281 if (!!this.retrySendmove)
282 clearInterval(this.retrySendmove);
283 if (!!this.clockUpdate)
284 clearInterval(this.clockUpdate);
285 this.send("disconnect");
287 roomInit: function() {
288 if (!this.roomInitialized) {
289 // Notify the room only now that I connected, because
290 // messages might be lost otherwise (if game loading is slow)
291 this.send("connect");
292 this.send("pollclients");
293 // We may ask fullgame several times if some moves are lost,
294 // but room should be init only once:
295 this.roomInitialized = true;
298 send: function(code, obj) {
300 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
302 isConnected: function(index) {
303 const player = this.game.players[index];
305 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
306 // Still have to check for name (because of potential multi-accounts
307 // on same browser, although this should be rare...)
308 return (!this.st.user.name || this.st.user.name == player.name);
309 // Try to find a match in people:
313 Object.keys(this.people).some(sid => sid == player.sid)
318 Object.values(this.people).some(p => p.id == player.uid)
322 resetChatColor: function() {
323 // TODO: this is called twice, once on opening an once on closing
324 document.getElementById("chatBtn").classList.remove("somethingnew");
326 processChat: function(chat) {
327 this.send("newchat", { data: chat });
328 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
329 if (this.game.type == "corr" && this.st.user.id > 0)
330 this.updateCorrGame({ chat: chat });
332 clearChat: function() {
333 // Nothing more to do if game is live (chats not recorded)
334 if (this.game.type == "corr") {
335 if (!!this.game.mycolor)
336 ajax("/chats", "DELETE", {gid: this.game.id});
337 this.$set(this.game, "chats", []);
340 // Notify turn after a new move (to opponent and me on MyGames page)
341 notifyTurn: function(sid) {
342 const player = this.people[sid];
343 const colorIdx = this.game.players.findIndex(
344 p => p.sid == sid || p.uid == player.id);
345 const color = ["w","b"][colorIdx];
346 const movesCount = this.game.moves.length;
348 (color == "w" && movesCount % 2 == 0) ||
349 (color == "b" && movesCount % 2 == 1);
350 this.send("turnchange", { target: sid, yourTurn: yourTurn });
352 showNextGame: function() {
353 if (this.nextIds.length == 0) return;
354 // Did I play in current game? If not, add it to nextIds list
355 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
356 this.nextIds.unshift(this.game.id);
357 const nextGid = this.nextIds.pop();
359 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
361 rematch: function() {
362 alert("Unimplemented yet (soon :) )");
363 // TODO: same logic as for draw, but re-click remove rematch offer (toggle)
365 askGameAgain: function() {
366 this.gameIsLoading = true;
367 const currentUrl = document.location.href;
368 const doAskGame = () => {
369 if (currentUrl != document.location.href) return; //page change
370 if (!this.gameRef.rid)
371 // This is my game: just reload.
374 // Just ask fullgame again (once!), this is much simpler.
375 // If this fails, the user could just reload page :/
376 this.send("askfullgame", { target: this.gameRef.rid });
377 this.askIfPeerConnected = setInterval(
380 !!this.people[this.gameRef.rid] &&
381 currentUrl != document.location.href
383 this.send("askfullgame", { target: this.gameRef.rid });
384 clearInterval(this.askIfPeerConnected);
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 });
473 this.askLastate = setInterval(
475 // Ask until we got a reply (or opponent disconnect):
476 if (!this.gotLastate && !!this.people[user.sid])
477 this.send("asklastate", { target: user.sid });
479 clearInterval(this.askLastate);
488 // Send current (live) game if not asked by any of the players
490 this.game.type == "live" &&
491 this.game.players.every(p => p.sid != data.from[0])
496 players: this.game.players,
498 cadence: this.game.cadence,
499 score: this.game.score,
500 rid: this.st.user.sid //useful in Hall if I'm an observer
502 this.send("game", { data: myGame, target: data.from });
506 const gameToSend = Object.keys(this.game)
509 "id","fen","players","vid","cadence","fenStart","vname",
510 "moves","clocks","initime","score","drawOffer"
514 obj[k] = this.game[k];
519 this.send("fullgame", { data: gameToSend, target: data.from });
522 // Callback "roomInit" to poll clients only after game is loaded
523 this.loadGame(data.data, this.roomInit);
526 // Sending informative last state if I played a move or score != "*"
528 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
529 this.game.score != "*" ||
530 this.drawOffer == "sent"
532 // Send our "last state" informations to opponent
533 const L = this.game.moves.length;
534 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
536 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
537 addTime: L > 0 ? this.game.addTimes[L - 1] : undefined,
538 // Since we played a move (or abort or resign),
539 // only drawOffer=="sent" is possible
540 drawSent: this.drawOffer == "sent",
541 score: this.game.score,
543 initime: this.game.initime[1 - myIdx] //relevant only if I played
545 this.send("lastate", { data: myLastate, target: data.from });
547 this.send("lastate", { data: {nothing: true}, target: data.from });
551 // Got opponent infos about last move
552 this.gotLastate = true;
553 if (!data.data.nothing) {
554 this.lastate = data.data;
555 if (this.game.rendered)
556 // Game is rendered (Board component)
557 this.processLastate();
558 // Else: will be processed when game is ready
563 const movePlus = data.data;
564 const movesCount = this.game.moves.length;
565 if (movePlus.index > movesCount) {
566 // This can only happen if I'm an observer and missed a move.
567 if (this.gotMoveIdx < movePlus.index)
568 this.gotMoveIdx = movePlus.index;
569 if (!this.gameIsLoading) this.askGameAgain();
573 movePlus.index < movesCount ||
574 this.gotMoveIdx >= movePlus.index
576 // Opponent re-send but we already have the move:
577 // (maybe he didn't receive our pingback...)
578 this.send("gotmove", {data: movePlus.index, target: data.from});
580 this.gotMoveIdx = movePlus.index;
581 const receiveMyMove = (movePlus.color == this.game.mycolor);
582 if (!receiveMyMove && !!this.game.mycolor)
583 // Notify opponent that I got the move:
584 this.send("gotmove", {data: movePlus.index, target: data.from});
585 if (movePlus.cancelDrawOffer) {
586 // Opponent refuses draw
588 // NOTE for corr games: drawOffer reset by player in turn
590 this.game.type == "live" &&
591 !!this.game.mycolor &&
594 GameStorage.update(this.gameRef.id, { drawOffer: "" });
597 this.$refs["basegame"].play(movePlus.move, "received", null, true);
601 addTime: movePlus.addTime,
602 receiveMyMove: receiveMyMove
610 this.opponentGotMove = true;
614 const score = data.side == "b" ? "1-0" : "0-1";
615 const side = data.side == "w" ? "White" : "Black";
616 this.gameOver(score, side + " surrender");
619 this.gameOver("?", "Stop");
622 this.gameOver("1/2", data.data);
625 // NOTE: observers don't know who offered draw
626 this.drawOffer = "received";
629 this.newChat = data.data;
630 if (!document.getElementById("modalChat").checked)
631 document.getElementById("chatBtn").classList.add("somethingnew");
635 socketCloseListener: function() {
636 this.conn = new WebSocket(this.connexionString);
637 this.conn.addEventListener("message", this.socketMessageListener);
638 this.conn.addEventListener("close", this.socketCloseListener);
640 updateCorrGame: function(obj) {
645 gid: this.gameRef.id,
650 // lastate was received, but maybe game wasn't ready yet:
651 processLastate: function() {
652 const data = this.lastate;
653 this.lastate = undefined; //security...
654 const L = this.game.moves.length;
655 if (data.movesCount > L) {
656 // Just got last move from him
657 this.$refs["basegame"].play(
661 {addTime: data.addTime, initime: data.initime}
664 if (data.drawSent) this.drawOffer = "received";
665 if (data.score != "*") {
667 if (this.game.score == "*") this.gameOver(data.score);
670 clickDraw: function() {
671 if (!this.game.mycolor) return; //I'm just spectator
672 if (["received", "threerep"].includes(this.drawOffer)) {
673 if (!confirm(this.st.tr["Accept draw?"])) return;
675 this.drawOffer == "received"
677 : "Three repetitions";
678 this.send("draw", { data: message });
679 this.gameOver("1/2", message);
680 } else if (this.drawOffer == "") {
681 // No effect if drawOffer == "sent"
682 if (this.game.mycolor != this.vr.turn) {
683 alert(this.st.tr["Draw offer only in your turn"]);
686 if (!confirm(this.st.tr["Offer draw?"])) return;
687 this.drawOffer = "sent";
688 this.send("drawoffer");
689 if (this.game.type == "live") {
692 { drawOffer: this.game.mycolor }
694 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
697 abortGame: function() {
698 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
699 this.gameOver("?", "Stop");
703 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
705 this.send("resign", { data: this.game.mycolor });
706 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
707 const side = this.game.mycolor == "w" ? "White" : "Black";
708 this.gameOver(score, side + " surrender");
710 // 3 cases for loading a game:
711 // - from indexedDB (running or completed live game I play)
712 // - from server (one correspondance game I play[ed] or not)
713 // - from remote peer (one live game I don't play, finished or not)
714 loadGame: function(game, callback) {
715 const afterRetrieval = async game => {
716 const vModule = await import("@/variants/" + game.vname + ".js");
717 window.V = vModule.VariantRules;
718 this.vr = new V(game.fen);
719 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
720 const tc = extractTime(game.cadence);
721 const myIdx = game.players.findIndex(p => {
722 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
724 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
725 if (!game.chats) game.chats = []; //live games don't have chat history
726 if (gtype == "corr") {
727 if (game.players[0].color == "b") {
728 // Adopt the same convention for live and corr games: [0] = white
729 [game.players[0], game.players[1]] = [
734 // NOTE: clocks in seconds, initime in milliseconds
735 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
736 game.clocks = [tc.mainTime, tc.mainTime];
737 const L = game.moves.length;
738 if (game.score == "*") {
739 // Set clocks + initime
740 game.initime = [0, 0];
742 const gameLastupdate = game.moves[L-1].played;
743 game.initime[L % 2] = gameLastupdate;
746 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
750 // Sort chat messages from newest to oldest
751 game.chats.sort((c1, c2) => {
752 return c2.added - c1.added;
754 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
755 // Did a chat message arrive after my last move?
757 if (L == 1 && myIdx == 0)
758 dtLastMove = game.moves[0].played;
761 // It's now white turn
762 dtLastMove = game.moves[L-1-(1-myIdx)].played;
765 dtLastMove = game.moves[L-1-myIdx].played;
768 if (dtLastMove < game.chats[0].added)
769 document.getElementById("chatBtn").classList.add("somethingnew");
771 // Now that we used idx and played, re-format moves as for live games
772 game.moves = game.moves.map(m => m.squares);
774 if (gtype == "live" && game.clocks[0] < 0) {
776 game.clocks = [tc.mainTime, tc.mainTime];
777 if (game.score == "*") {
778 game.initime[0] = Date.now();
780 // I play in this live game; corr games don't have clocks+initime
781 GameStorage.update(game.id, {
783 initime: game.initime
788 if (!!game.drawOffer) {
789 if (game.drawOffer == "t")
791 this.drawOffer = "threerep";
793 // Draw offered by any of the players:
794 if (myIdx < 0) this.drawOffer = "received";
796 // I play in this game:
798 (game.drawOffer == "w" && myIdx == 0) ||
799 (game.drawOffer == "b" && myIdx == 1)
801 this.drawOffer = "sent";
802 else this.drawOffer = "received";
806 this.repeat = {}; //reset: scan past moves' FEN:
808 let vr_tmp = new V(game.fenStart);
810 game.moves.forEach(m => {
812 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
813 this.repeat[fenIdx] = this.repeat[fenIdx]
814 ? this.repeat[fenIdx] + 1
817 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
818 this.game = Object.assign(
819 // NOTE: assign mycolor here, since BaseGame could also be VS computer
822 increment: tc.increment,
824 // opponent sid not strictly required (or available), but easier
825 // at least oppsid or oppid is available anyway:
826 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
827 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
828 addTimes: [], //used for live games
832 if (this.gameIsLoading)
833 // Re-load game because we missed some moves:
834 // artificially reset BaseGame (required if moves arrived in wrong order)
835 this.$refs["basegame"].re_setVariables();
838 this.gotMoveIdx = game.moves.length - 1;
840 this.$nextTick(() => {
841 this.game.rendered = true;
842 // Did lastate arrive before game was rendered?
843 if (this.lastate) this.processLastate();
845 if (this.gameIsLoading) {
846 this.gameIsLoading = false;
847 if (this.gotMoveIdx >= game.moves.length)
848 // Some moves arrived meanwhile...
851 if (!!callback) callback();
854 afterRetrieval(game);
857 if (this.gameRef.rid) {
858 // Remote live game: forgetting about callback func... (TODO: design)
859 this.send("askfullgame", { target: this.gameRef.rid });
861 // Local or corr game on server.
862 // NOTE: afterRetrieval() is never called if game not found
863 const gid = this.gameRef.id;
864 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
865 // corr games identifiers are integers
866 ajax("/games", "GET", { gid: gid }, res => {
868 g.moves.forEach(m => {
869 m.squares = JSON.parse(m.squares);
876 GameStorage.get(this.gameRef.id, afterRetrieval);
879 re_setClocks: function() {
880 if (this.game.moves.length < 2 || this.game.score != "*") {
881 // 1st move not completed yet, or game over: freeze time
882 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
885 const currentTurn = this.vr.turn;
886 const currentMovesCount = this.game.moves.length;
887 const colorIdx = ["w", "b"].indexOf(currentTurn);
889 this.game.clocks[colorIdx] -
890 (Date.now() - this.game.initime[colorIdx]) / 1000;
891 this.virtualClocks = [0, 1].map(i => {
893 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
894 return ppt(this.game.clocks[i] - removeTime).split(':');
896 this.clockUpdate = setInterval(() => {
899 this.game.moves.length > currentMovesCount ||
900 this.game.score != "*"
902 clearInterval(this.clockUpdate);
905 currentTurn == "w" ? "0-1" : "1-0",
912 ppt(Math.max(0, --countdown)).split(':')
916 // Update variables and storage after a move:
917 processMove: function(move, data) {
918 if (!data) data = {};
919 const moveCol = this.vr.turn;
920 const doProcessMove = () => {
921 const colorIdx = ["w", "b"].indexOf(moveCol);
922 const nextIdx = 1 - colorIdx;
923 const origMovescount = this.game.moves.length;
925 this.game.type == "live"
926 ? (data.addTime || 0)
928 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
929 if (this.drawOffer == "received")
932 if (this.game.type == "live" && origMovescount >= 2) {
933 const elapsed = Date.now() - this.game.initime[colorIdx];
934 // elapsed time is measured in milliseconds
935 addTime = this.game.increment - elapsed / 1000;
938 // Update current game object:
939 playMove(move, this.vr);
940 // TODO: notifyTurn: "changeturn" message
941 this.game.moves.push(move);
942 // (add)Time indication: useful in case of lastate infos requested
943 if (this.game.type == "live")
944 this.game.addTimes.push(addTime);
945 this.game.fen = this.vr.getFen();
946 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
947 // In corr games, just reset clock to mainTime:
948 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
949 // data.initime is set only when I receive a "lastate" move from opponent
950 this.game.initime[nextIdx] = data.initime || Date.now();
951 // If repetition detected, consider that a draw offer was received:
952 const fenObj = this.vr.getFenForRepeat();
953 this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1;
954 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
955 else if (this.drawOffer == "threerep") this.drawOffer = "";
956 if (!!this.game.mycolor && !data.receiveMyMove) {
957 // NOTE: 'var' to see that variable outside this block
958 var filtered_move = getFilteredMove(move);
960 // Since corr games are stored at only one location, update should be
961 // done only by one player for each move:
963 !!this.game.mycolor &&
964 !data.receiveMyMove &&
965 (this.game.type == "live" || moveCol == this.game.mycolor)
968 switch (this.drawOffer) {
973 drawCode = this.game.mycolor;
976 drawCode = V.GetOppCol(this.game.mycolor);
979 if (this.game.type == "corr") {
980 // corr: only move, fen and score
981 this.updateCorrGame({
984 squares: filtered_move,
988 // Code "n" for "None" to force reset (otherwise it's ignored)
989 drawOffer: drawCode || "n"
993 const updateStorage = () => {
994 GameStorage.update(this.gameRef.id, {
997 moveIdx: origMovescount,
998 clocks: this.game.clocks,
999 initime: this.game.initime,
1003 // The active tab can update storage immediately
1004 if (!document.hidden) updateStorage();
1005 // Small random delay otherwise
1006 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1009 // Send move ("newmove" event) to people in the room (if our turn)
1010 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1012 move: filtered_move,
1013 index: origMovescount,
1014 // color is required to check if this is my move (if several tabs opened)
1016 addTime: addTime, //undefined for corr games
1017 cancelDrawOffer: this.drawOffer == ""
1019 this.opponentGotMove = false;
1020 this.send("newmove", {data: sendMove});
1021 // If the opponent doesn't reply gotmove soon enough, re-send move:
1022 this.retrySendmove = setInterval(
1024 if (this.opponentGotMove) {
1025 clearInterval(this.retrySendmove);
1028 let oppsid = this.game.players[nextIdx].sid;
1030 oppsid = Object.keys(this.people).find(
1031 sid => this.people[sid].id == this.game.players[nextIdx].uid
1034 if (!oppsid || !this.people[oppsid])
1035 // Opponent is disconnected: he'll ask last state
1036 clearInterval(this.retrySendmove);
1037 else this.send("newmove", {data: sendMove, target: oppsid});
1044 this.game.type == "corr" &&
1045 moveCol == this.game.mycolor &&
1048 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1049 // We may play several moves in a row: in case of, remove listener:
1050 let elClone = el.cloneNode(true);
1051 el.parentNode.replaceChild(elClone, el);
1052 elClone.addEventListener(
1055 document.getElementById("modalConfirm").checked = false;
1057 if (this.st.settings.gotonext) this.showNextGame();
1058 else this.re_setClocks();
1061 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1062 V.PlayOnBoard(this.vr.board, move);
1063 const position = this.vr.getBaseFen();
1064 V.UndoOnBoard(this.vr.board, move);
1065 this.curDiag = getDiagram({
1067 orientation: V.CanFlip ? this.game.mycolor : "w"
1069 document.getElementById("modalConfirm").checked = true;
1073 this.re_setClocks();
1076 cancelMove: function() {
1077 document.getElementById("modalConfirm").checked = false;
1078 this.$refs["basegame"].cancelLastMove();
1080 gameOver: function(score, scoreMsg) {
1081 this.game.score = score;
1082 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
1083 const myIdx = this.game.players.findIndex(p => {
1084 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1087 // OK, I play in this game
1092 if (this.Game.type == "live")
1093 GameStorage.update(this.gameRef.id, scoreObj);
1094 else this.updateCorrGame(scoreObj);
1095 // Notify the score to main Hall. TODO: only one player (currently double send)
1096 this.send("result", { gid: this.game.id, score: score });
1103 <style lang="sass" scoped>
1105 background-color: lightgreen
1117 @media screen and (min-width: 768px)
1120 @media screen and (max-width: 767px)
1125 display: inline-block
1129 display: inline-block
1131 display: inline-flex
1135 @media screen and (max-width: 767px)
1138 @media screen and (max-width: 767px)
1141 @media screen and (min-width: 768px)
1153 background-color: #edda99
1155 display: inline-block
1164 display: inline-block
1177 animation: blink-animation 2s steps(3, start) infinite
1178 @keyframes blink-animation
1183 display: inline-block
1195 .draw-sent, .draw-sent:hover
1196 background-color: lightyellow
1198 .draw-received, .draw-received:hover
1199 background-color: lightgreen
1201 .draw-threerep, .draw-threerep:hover
1202 background-color: #e4d1fc
1205 background-color: #c5fefe
1210 // width: 100% required for Firefox
1220 background-color: lightgreen
1222 background-color: red