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)")
23 :players="game.players"
24 :pastChats="game.chats"
27 @chatcleared="clearChat"
29 input#modalConfirm.modal(type="checkbox")
30 div#confirmDiv(role="dialog")
32 .diagram(v-html="curDiag")
33 .button-group#buttonsConfirm
34 // onClick for acceptBtn: set dynamically
36 span {{ st.tr["Validate"] }}
37 button.refuseBtn(@click="cancelMove()")
38 span {{ st.tr["Cancel"] }}
40 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
41 span.variant-cadence {{ game.cadence }}
42 span.variant-name {{ game.vname }}
44 v-if="nextIds.length > 0"
45 @click="showNextGame()"
47 | {{ st.tr["Next_g"] }}
48 button#chatBtn.tooltip(
49 onClick="window.doClick('modalChat')"
52 img(src="/images/icons/chat.svg")
53 #actions(v-if="game.score=='*'")
56 :class="{['draw-' + drawOffer]: true}"
57 :aria-label="st.tr['Draw']"
59 img(src="/images/icons/draw.svg")
63 :aria-label="st.tr['Abort']"
65 img(src="/images/icons/abort.svg")
69 :aria-label="st.tr['Resign']"
71 img(src="/images/icons/resign.svg")
73 v-else-if="!!game.mycolor"
75 :aria-label="st.tr['Rematch']"
77 img(src="/images/icons/rematch.svg")
80 span.name(:class="{connected: isConnected(0)}")
81 | {{ game.players[0].name || "@nonymous" }}
83 v-if="game.score=='*'"
84 :class="{yourturn: !!vr && vr.turn == 'w'}"
86 span.time-left {{ virtualClocks[0][0] }}
87 span.time-separator(v-if="!!virtualClocks[0][1]") :
88 span.time-right(v-if="!!virtualClocks[0][1]") {{ virtualClocks[0][1] }}
90 span.name(:class="{connected: isConnected(1)}")
91 | {{ game.players[1].name || "@nonymous" }}
93 v-if="game.score=='*'"
94 :class="{yourturn: !!vr && vr.turn == 'b'}"
96 span.time-left {{ virtualClocks[1][0] }}
97 span.time-separator(v-if="!!virtualClocks[1][1]") :
98 span.time-right(v-if="!!virtualClocks[1][1]") {{ virtualClocks[1][1] }}
102 @newmove="processMove"
108 import BaseGame from "@/components/BaseGame.vue";
109 import Chat from "@/components/Chat.vue";
110 import { store } from "@/store";
111 import { GameStorage } from "@/utils/gameStorage";
112 import { ppt } from "@/utils/datetime";
113 import { ajax } from "@/utils/ajax";
114 import { extractTime } from "@/utils/timeControl";
115 import { getRandString } from "@/utils/alea";
116 import { getDiagram } from "@/utils/printDiagram";
117 import { processModalClick } from "@/utils/modalClick";
118 import { playMove, getFilteredMove } from "@/utils/playUndo";
119 import { getScoreMessage } from "@/utils/scoring";
120 import { ArrayFun } from "@/utils/array";
121 import params from "@/parameters";
128 // gameRef: to find the game in (potentially remote) storage
133 // rid = remote (socket) ID
138 // Passed to BaseGame
139 players: [{ name: "" }, { name: "" }],
144 virtualClocks: [[0,0], [0,0]], //initialized with true game.clocks
145 vr: null, //"variant rules" object initialized from FEN
147 people: {}, //players + observers
148 onMygames: [], //opponents (or me) on "MyGames" page
149 lastate: undefined, //used if opponent send lastate before game is ready
150 repeat: {}, //detect position repetition
151 curDiag: "", //for corr moves confirmation
154 roomInitialized: false,
155 // If newmove has wrong index: ask fullgame again:
157 gameIsLoading: false,
158 // If asklastate got no reply, ask again:
160 gotMoveIdx: -1, //last move index received
161 // If newmove got no pingback, send again:
162 opponentGotMove: false,
164 // Related to (killing of) self multi-connects:
170 $route: function(to) {
171 this.gameRef.id = to.params["id"];
172 this.gameRef.rid = to.query["rid"];
176 // NOTE: some redundant code with Hall.vue (mostly related to people array)
177 created: function() {
178 // Always add myself to players' list
179 const my = this.st.user;
180 this.$set(this.people, my.sid, { id: my.id, name: my.name });
181 this.gameRef.id = this.$route.params["id"];
182 // rid = remote ID to find an observed live game,
183 // next = next corr games IDs to navigate faster
184 // (Both might be undefined)
185 this.gameRef.rid = this.$route.query["rid"];
186 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
187 // Initialize connection
188 this.connexionString =
195 // Discard potential "/?next=[...]" for page indication:
196 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
197 this.conn = new WebSocket(this.connexionString);
198 this.conn.onmessage = this.socketMessageListener;
199 this.conn.onclose = this.socketCloseListener;
200 // Socket init required before loading remote game:
201 const socketInit = callback => {
202 if (!!this.conn && this.conn.readyState == 1)
206 // Socket not ready yet (initial loading)
207 // NOTE: it's important to call callback without arguments,
208 // otherwise first arg is Websocket object and loadGame fails.
209 this.conn.onopen = () => callback();
211 if (!this.gameRef.rid)
212 // Game stored locally or on server
213 this.loadGame(null, () => socketInit(this.roomInit));
215 // Game stored remotely: need socket to retrieve it
216 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
217 // --> It will be given when receiving "fullgame" socket event.
218 socketInit(this.loadGame);
220 mounted: function() {
222 .getElementById("chatWrap")
223 .addEventListener("click", processModalClick);
224 if ("ontouchstart" in window) {
225 // Disable tooltips on smartphones:
226 document.getElementsByClassName("tooltip").forEach(elt => {
227 elt.classList.remove("tooltip");
231 beforeDestroy: function() {
232 this.send("disconnect");
235 roomInit: function() {
236 if (!this.roomInitialized) {
237 // Notify the room only now that I connected, because
238 // messages might be lost otherwise (if game loading is slow)
239 this.send("connect");
240 this.send("pollclients");
241 // We may ask fullgame several times if some moves are lost,
242 // but room should be init only once:
243 this.roomInitialized = true;
246 send: function(code, obj) {
248 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
250 isConnected: function(index) {
251 const player = this.game.players[index];
253 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
254 // Still have to check for name (because of potential multi-accounts
255 // on same browser, although this should be rare...)
256 return (!this.st.user.name || this.st.user.name == player.name);
257 // Try to find a match in people:
261 Object.keys(this.people).some(sid => sid == player.sid)
266 Object.values(this.people).some(p => p.id == player.uid)
270 resetChatColor: function() {
271 // TODO: this is called twice, once on opening an once on closing
272 document.getElementById("chatBtn").classList.remove("somethingnew");
274 processChat: function(chat) {
275 this.send("newchat", { data: chat });
276 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
277 if (this.game.type == "corr" && this.st.user.id > 0)
278 GameStorage.update(this.gameRef.id, { chat: chat });
280 clearChat: function() {
281 // Nothing more to do if game is live (chats not recorded)
282 if (this.game.type == "corr") {
283 if (!!this.game.mycolor)
284 ajax("/chats", "DELETE", {gid: this.game.id});
285 this.$set(this.game, "chats", []);
288 // Notify turn after a new move (to opponent and me on MyGames page)
289 notifyTurn: function(sid) {
290 const player = this.people[sid];
291 const colorIdx = this.game.players.findIndex(
292 p => p.sid == sid || p.uid == player.id);
293 const color = ["w","b"][colorIdx];
294 const movesCount = this.game.moves.length;
296 (color == "w" && movesCount % 2 == 0) ||
297 (color == "b" && movesCount % 2 == 1);
298 this.send("turnchange", { target: sid, yourTurn: yourTurn });
300 showNextGame: function() {
301 // Did I play in current game? If not, add it to nextIds list
302 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
303 this.nextIds.unshift(this.game.id);
304 const nextGid = this.nextIds.pop();
306 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
308 rematch: function() {
309 alert("Unimplemented yet (soon :) )");
310 // TODO: same logic as for draw, but re-click remove rematch offer (toggle)
312 askGameAgain: function() {
313 this.gameIsLoading = true;
314 const doAskGame = () => {
315 if (!this.gameRef.rid)
316 // This is my game: just reload.
319 // Just ask fullgame again (once!), this is much simpler.
320 // If this fails, the user could just reload page :/
322 (function askIfPeerConnected() {
323 if (!!self.people[self.gameRef.rid])
324 self.send("askfullgame", { target: self.gameRef.rid });
325 else setTimeout(askIfPeerConnected, 1000);
329 // Delay of at least 2s between two game requests
330 const now = Date.now();
331 const delay = Math.max(2000 - (now - this.askGameTime), 0);
332 this.askGameTime = now;
333 setTimeout(doAskGame, delay);
335 socketMessageListener: function(msg) {
336 if (!this.conn) return;
337 const data = JSON.parse(msg.data);
340 data.sockIds.forEach(sid => {
341 if (sid != this.st.user.sid)
342 this.send("askidentity", { target: sid });
346 if (!this.people[data.from]) {
347 this.newConnect[data.from] = true; //for self multi-connects tests
348 this.send("askidentity", { target: data.from });
352 this.$delete(this.people, data.from);
355 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
356 // Either me (another tab) or opponent
357 const sid = data.from;
358 if (!this.onMygames.some(s => s == sid))
360 this.onMygames.push(sid);
361 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
364 if (!this.people[sid])
365 this.send("askidentity", { target: sid });
368 ArrayFun.remove(this.onMygames, sid => sid == data.from);
371 // I logged in elsewhere:
373 alert(this.st.tr["New connexion detected: tab now offline"]);
375 case "askidentity": {
376 // Request for identification
378 // Decompose to avoid revealing email
379 name: this.st.user.name,
380 sid: this.st.user.sid,
383 this.send("identity", { data: me, target: data.from });
387 const user = data.data;
388 this.$set(this.people, user.sid, { name: user.name, id: user.id });
389 // If I multi-connect, kill current connexion if no mark (I'm older)
390 if (this.newConnect[user.sid]) {
393 user.id == this.st.user.id &&
394 user.sid != this.st.user.sid &&
395 !this.killed[this.st.user.sid]
397 this.send("killme", { sid: this.st.user.sid });
398 this.killed[this.st.user.sid] = true;
400 delete this.newConnect[user.sid];
402 if (!this.killed[this.st.user.sid]) {
403 // Ask potentially missed last state, if opponent and I play
405 !!this.game.mycolor &&
406 this.game.type == "live" &&
407 this.game.score == "*" &&
408 this.game.players.some(p => p.sid == user.sid)
411 (function askLastate() {
412 self.send("asklastate", { target: user.sid });
415 // Ask until we got a reply (or opponent disconnect):
416 if (!self.gotLastate && !!self.people[user.sid])
427 // Send current (live) game if not asked by any of the players
429 this.game.type == "live" &&
430 this.game.players.every(p => p.sid != data.from[0])
435 players: this.game.players,
437 cadence: this.game.cadence,
438 score: this.game.score,
439 rid: this.st.user.sid //useful in Hall if I'm an observer
441 this.send("game", { data: myGame, target: data.from });
445 const gameToSend = Object.keys(this.game)
448 "id","fen","players","vid","cadence","fenStart","vname",
449 "moves","clocks","initime","score","drawOffer"
453 obj[k] = this.game[k];
458 this.send("fullgame", { data: gameToSend, target: data.from });
461 // Callback "roomInit" to poll clients only after game is loaded
462 this.loadGame(data.data, this.roomInit);
465 // Sending informative last state if I played a move or score != "*"
467 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
468 this.game.score != "*" ||
469 this.drawOffer == "sent"
471 // Send our "last state" informations to opponent
472 const L = this.game.moves.length;
473 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
475 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
476 addTime: L > 0 ? this.game.addTimes[L - 1] : undefined,
477 // Since we played a move (or abort or resign),
478 // only drawOffer=="sent" is possible
479 drawSent: this.drawOffer == "sent",
480 score: this.game.score,
482 initime: this.game.initime[1 - myIdx] //relevant only if I played
484 this.send("lastate", { data: myLastate, target: data.from });
486 this.send("lastate", { data: {nothing: true}, target: data.from });
490 // Got opponent infos about last move
491 this.gotLastate = true;
492 if (!data.data.nothing) {
493 this.lastate = data.data;
494 if (this.game.rendered)
495 // Game is rendered (Board component)
496 this.processLastate();
497 // Else: will be processed when game is ready
502 const movePlus = data.data;
503 const movesCount = this.game.moves.length;
504 if (movePlus.index > movesCount) {
505 // This can only happen if I'm an observer and missed a move.
506 if (this.gotMoveIdx < movePlus.index)
507 this.gotMoveIdx = movePlus.index;
508 if (!this.gameIsLoading) this.askGameAgain();
512 movePlus.index < movesCount ||
513 this.gotMoveIdx >= movePlus.index
515 // Opponent re-send but we already have the move:
516 // (maybe he didn't receive our pingback...)
517 this.send("gotmove", {data: movePlus.index, target: data.from});
519 this.gotMoveIdx = movePlus.index;
520 const receiveMyMove = (movePlus.color == this.game.mycolor);
521 if (!receiveMyMove && !!this.game.mycolor)
522 // Notify opponent that I got the move:
523 this.send("gotmove", {data: movePlus.index, target: data.from});
524 if (movePlus.cancelDrawOffer) {
525 // Opponent refuses draw
527 // NOTE for corr games: drawOffer reset by player in turn
529 this.game.type == "live" &&
530 !!this.game.mycolor &&
533 GameStorage.update(this.gameRef.id, { drawOffer: "" });
536 this.$refs["basegame"].play(movePlus.move, "received", null, true);
540 addTime: movePlus.addTime,
541 receiveMyMove: receiveMyMove
549 this.opponentGotMove = true;
553 const score = data.side == "b" ? "1-0" : "0-1";
554 const side = data.side == "w" ? "White" : "Black";
555 this.gameOver(score, side + " surrender");
558 this.gameOver("?", "Stop");
561 this.gameOver("1/2", data.data);
564 // NOTE: observers don't know who offered draw
565 this.drawOffer = "received";
568 this.newChat = data.data;
569 if (!document.getElementById("modalChat").checked)
570 document.getElementById("chatBtn").classList.add("somethingnew");
574 socketCloseListener: function() {
575 this.conn = new WebSocket(this.connexionString);
576 this.conn.addEventListener("message", this.socketMessageListener);
577 this.conn.addEventListener("close", this.socketCloseListener);
579 // lastate was received, but maybe game wasn't ready yet:
580 processLastate: function() {
581 const data = this.lastate;
582 this.lastate = undefined; //security...
583 const L = this.game.moves.length;
584 if (data.movesCount > L) {
585 // Just got last move from him
586 this.$refs["basegame"].play(
590 {addTime: data.addTime, initime: data.initime}
593 if (data.drawSent) this.drawOffer = "received";
594 if (data.score != "*") {
596 if (this.game.score == "*") this.gameOver(data.score);
599 clickDraw: function() {
600 if (!this.game.mycolor) return; //I'm just spectator
601 if (["received", "threerep"].includes(this.drawOffer)) {
602 if (!confirm(this.st.tr["Accept draw?"])) return;
604 this.drawOffer == "received"
606 : "Three repetitions";
607 this.send("draw", { data: message });
608 this.gameOver("1/2", message);
609 } else if (this.drawOffer == "") {
610 // No effect if drawOffer == "sent"
611 if (this.game.mycolor != this.vr.turn) {
612 alert(this.st.tr["Draw offer only in your turn"]);
615 if (!confirm(this.st.tr["Offer draw?"])) return;
616 this.drawOffer = "sent";
617 this.send("drawoffer");
618 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
621 abortGame: function() {
622 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
623 this.gameOver("?", "Stop");
627 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
629 this.send("resign", { data: this.game.mycolor });
630 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
631 const side = this.game.mycolor == "w" ? "White" : "Black";
632 this.gameOver(score, side + " surrender");
634 // 3 cases for loading a game:
635 // - from indexedDB (running or completed live game I play)
636 // - from server (one correspondance game I play[ed] or not)
637 // - from remote peer (one live game I don't play, finished or not)
638 loadGame: function(game, callback) {
639 const afterRetrieval = async game => {
640 const vModule = await import("@/variants/" + game.vname + ".js");
641 window.V = vModule.VariantRules;
642 this.vr = new V(game.fen);
643 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
644 const tc = extractTime(game.cadence);
645 const myIdx = game.players.findIndex(p => {
646 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
648 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
649 if (!game.chats) game.chats = []; //live games don't have chat history
650 if (gtype == "corr") {
651 if (game.players[0].color == "b") {
652 // Adopt the same convention for live and corr games: [0] = white
653 [game.players[0], game.players[1]] = [
658 // NOTE: clocks in seconds, initime in milliseconds
659 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
660 game.clocks = [tc.mainTime, tc.mainTime];
661 const L = game.moves.length;
662 if (game.score == "*") {
663 // Set clocks + initime
664 game.initime = [0, 0];
666 const gameLastupdate = game.moves[L-1].played;
667 game.initime[L % 2] = gameLastupdate;
670 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
674 // Sort chat messages from newest to oldest
675 game.chats.sort((c1, c2) => {
676 return c2.added - c1.added;
678 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
679 // Did a chat message arrive after my last move?
681 if (L == 1 && myIdx == 0)
682 dtLastMove = game.moves[0].played;
685 // It's now white turn
686 dtLastMove = game.moves[L-1-(1-myIdx)].played;
689 dtLastMove = game.moves[L-1-myIdx].played;
692 if (dtLastMove < game.chats[0].added)
693 document.getElementById("chatBtn").classList.add("somethingnew");
695 // Now that we used idx and played, re-format moves as for live games
696 game.moves = game.moves.map(m => m.squares);
698 if (gtype == "live" && game.clocks[0] < 0) {
700 game.clocks = [tc.mainTime, tc.mainTime];
701 if (game.score == "*") {
702 game.initime[0] = Date.now();
704 // I play in this live game; corr games don't have clocks+initime
705 GameStorage.update(game.id, {
707 initime: game.initime
712 if (!!game.drawOffer) {
713 if (game.drawOffer == "t")
715 this.drawOffer = "threerep";
717 // Draw offered by any of the players:
718 if (myIdx < 0) this.drawOffer = "received";
720 // I play in this game:
722 (game.drawOffer == "w" && myIdx == 0) ||
723 (game.drawOffer == "b" && myIdx == 1)
725 this.drawOffer = "sent";
726 else this.drawOffer = "received";
730 this.repeat = {}; //reset: scan past moves' FEN:
732 let vr_tmp = new V(game.fenStart);
734 game.moves.forEach(m => {
736 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
737 this.repeat[fenIdx] = this.repeat[fenIdx]
738 ? this.repeat[fenIdx] + 1
741 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
742 this.game = Object.assign(
743 // NOTE: assign mycolor here, since BaseGame could also be VS computer
746 increment: tc.increment,
748 // opponent sid not strictly required (or available), but easier
749 // at least oppsid or oppid is available anyway:
750 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
751 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
752 addTimes: [], //used for live games
756 if (this.gameIsLoading)
757 // Re-load game because we missed some moves:
758 // artificially reset BaseGame (required if moves arrived in wrong order)
759 this.$refs["basegame"].re_setVariables();
761 this.$nextTick(() => {
762 this.game.rendered = true;
763 // Did lastate arrive before game was rendered?
764 if (this.lastate) this.processLastate();
766 if (this.gameIsLoading) {
767 this.gameIsLoading = false;
768 if (this.gotMoveIdx >= game.moves.length)
769 // Some moves arrived meanwhile...
772 if (!!callback) callback();
775 afterRetrieval(game);
778 if (this.gameRef.rid) {
779 // Remote live game: forgetting about callback func... (TODO: design)
780 this.send("askfullgame", { target: this.gameRef.rid });
782 // Local or corr game
783 // NOTE: afterRetrieval() is never called if game not found
784 GameStorage.get(this.gameRef.id, afterRetrieval);
787 re_setClocks: function() {
788 if (this.game.moves.length < 2 || this.game.score != "*") {
789 // 1st move not completed yet, or game over: freeze time
790 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
793 const currentTurn = this.vr.turn;
794 const currentMovesCount = this.game.moves.length;
795 const colorIdx = ["w", "b"].indexOf(currentTurn);
797 this.game.clocks[colorIdx] -
798 (Date.now() - this.game.initime[colorIdx]) / 1000;
799 this.virtualClocks = [0, 1].map(i => {
801 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
802 return ppt(this.game.clocks[i] - removeTime).split(':');
804 let clockUpdate = setInterval(() => {
807 this.game.moves.length > currentMovesCount ||
808 this.game.score != "*"
810 clearInterval(clockUpdate);
813 currentTurn == "w" ? "0-1" : "1-0",
820 ppt(Math.max(0, --countdown)).split(':')
824 // Update variables and storage after a move:
825 processMove: function(move, data) {
826 if (!data) data = {};
827 const moveCol = this.vr.turn;
828 const doProcessMove = () => {
829 const colorIdx = ["w", "b"].indexOf(moveCol);
830 const nextIdx = 1 - colorIdx;
831 const origMovescount = this.game.moves.length;
833 this.game.type == "live"
834 ? (data.addTime || 0)
836 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
837 if (this.drawOffer == "received")
840 if (this.game.type == "live" && origMovescount >= 2) {
841 const elapsed = Date.now() - this.game.initime[colorIdx];
842 // elapsed time is measured in milliseconds
843 addTime = this.game.increment - elapsed / 1000;
846 // Update current game object:
847 playMove(move, this.vr);
848 // TODO: notifyTurn: "changeturn" message
849 this.game.moves.push(move);
850 // (add)Time indication: useful in case of lastate infos requested
851 if (this.game.type == "live")
852 this.game.addTimes.push(addTime);
853 this.game.fen = this.vr.getFen();
854 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
855 // In corr games, just reset clock to mainTime:
856 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
857 // data.initime is set only when I receive a "lastate" move from opponent
858 this.game.initime[nextIdx] = data.initime || Date.now();
860 // If repetition detected, consider that a draw offer was received:
861 const fenObj = this.vr.getFenForRepeat();
862 this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1;
863 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
864 else if (this.drawOffer == "threerep") this.drawOffer = "";
865 // Since corr games are stored at only one location, update should be
866 // done only by one player for each move:
867 if (!!this.game.mycolor && !data.receiveMyMove) {
868 // NOTE: 'var' to see that variable outside this block
869 var filtered_move = getFilteredMove(move);
872 !!this.game.mycolor &&
873 !data.receiveMyMove &&
874 (this.game.type == "live" || moveCol == this.game.mycolor)
877 switch (this.drawOffer) {
882 drawCode = this.game.mycolor;
885 drawCode = V.GetOppCol(this.game.mycolor);
888 if (this.game.type == "corr") {
889 GameStorage.update(this.gameRef.id, {
892 squares: filtered_move,
896 // Code "n" for "None" to force reset (otherwise it's ignored)
897 drawOffer: drawCode || "n"
901 const updateStorage = () => {
902 GameStorage.update(this.gameRef.id, {
905 moveIdx: origMovescount,
906 clocks: this.game.clocks,
907 initime: this.game.initime,
911 // The active tab can update storage immediately
912 if (!document.hidden) updateStorage();
913 // Small random delay otherwise
914 else setTimeout(updateStorage, 500 + 1000 * Math.random());
917 // Send move ("newmove" event) to people in the room (if our turn)
918 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
921 index: origMovescount,
922 // color is required to check if this is my move (if several tabs opened)
924 addTime: addTime, //undefined for corr games
925 cancelDrawOffer: this.drawOffer == ""
927 this.opponentGotMove = false;
928 this.send("newmove", {data: sendMove});
929 // If the opponent doesn't reply gotmove soon enough, re-send move:
930 let retrySendmove = setInterval(
932 if (this.opponentGotMove) {
933 clearInterval(retrySendmove);
936 let oppsid = this.game.players[nextIdx].sid;
938 oppsid = Object.keys(this.people).find(
939 sid => this.people[sid].id == this.game.players[nextIdx].uid
942 if (!oppsid || !this.people[oppsid])
943 // Opponent is disconnected: he'll ask last state
944 clearInterval(retrySendmove);
945 else this.send("newmove", {data: sendMove, target: oppsid});
952 this.game.type == "corr" &&
953 moveCol == this.game.mycolor &&
956 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
957 // We may play several moves in a row: in case of, remove listener:
958 let elClone = el.cloneNode(true);
959 el.parentNode.replaceChild(elClone, el);
960 elClone.addEventListener(
963 document.getElementById("modalConfirm").checked = false;
968 const parsedFen = V.ParseFen(this.vr.getFen());
970 this.curDiag = getDiagram({
971 position: parsedFen.position,
972 orientation: this.game.mycolor
974 document.getElementById("modalConfirm").checked = true;
976 else doProcessMove();
978 cancelMove: function() {
979 document.getElementById("modalConfirm").checked = false;
980 this.$refs["basegame"].cancelLastMove();
982 gameOver: function(score, scoreMsg) {
983 this.game.score = score;
984 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
985 const myIdx = this.game.players.findIndex(p => {
986 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
989 // OK, I play in this game
990 GameStorage.update(this.gameRef.id, {
994 // Notify the score to main Hall. TODO: only one player (currently double send)
995 this.send("result", { gid: this.game.id, score: score });
1002 <style lang="sass" scoped>
1004 background-color: lightgreen
1016 @media screen and (min-width: 768px)
1019 @media screen and (max-width: 767px)
1024 display: inline-block
1028 display: inline-block
1030 display: inline-flex
1034 @media screen and (max-width: 767px)
1037 @media screen and (max-width: 767px)
1040 @media screen and (min-width: 768px)
1052 background-color: #edda99
1054 display: inline-block
1063 display: inline-block
1076 animation: blink-animation 2s steps(3, start) infinite
1077 @keyframes blink-animation
1082 display: inline-block
1094 .draw-sent, .draw-sent:hover
1095 background-color: lightyellow
1097 .draw-received, .draw-received:hover
1098 background-color: lightgreen
1100 .draw-threerep, .draw-threerep:hover
1101 background-color: #e4d1fc
1104 background-color: #c5fefe
1109 // width: 100% required for Firefox
1119 background-color: lightgreen
1121 background-color: red