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"
30 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
31 span.variant-cadence {{ game.cadence }}
32 span.variant-name {{ game.vname }}
34 v-if="nextIds.length > 0"
35 @click="showNextGame()"
37 | {{ st.tr["Next_g"] }}
38 button#chatBtn.tooltip(
39 onClick="window.doClick('modalChat')"
42 img(src="/images/icons/chat.svg")
43 #actions(v-if="game.score=='*'")
46 :class="{['draw-' + drawOffer]: true}"
47 :aria-label="st.tr['Draw']"
49 img(src="/images/icons/draw.svg")
53 :aria-label="st.tr['Abort']"
55 img(src="/images/icons/abort.svg")
59 :aria-label="st.tr['Resign']"
61 img(src="/images/icons/resign.svg")
63 v-else-if="!!game.mycolor"
65 :aria-label="st.tr['Rematch']"
67 img(src="/images/icons/rematch.svg")
70 span.name(:class="{connected: isConnected(0)}")
71 | {{ game.players[0].name || "@nonymous" }}
73 v-if="game.score=='*'"
74 :class="{yourturn: !!vr && vr.turn == 'w'}"
76 span.time-left {{ virtualClocks[0][0] }}
77 span.time-separator(v-if="!!virtualClocks[0][1]") :
78 span.time-right(v-if="!!virtualClocks[0][1]") {{ virtualClocks[0][1] }}
80 span.name(:class="{connected: isConnected(1)}")
81 | {{ game.players[1].name || "@nonymous" }}
83 v-if="game.score=='*'"
84 :class="{yourturn: !!vr && vr.turn == 'b'}"
86 span.time-left {{ virtualClocks[1][0] }}
87 span.time-separator(v-if="!!virtualClocks[1][1]") :
88 span.time-right(v-if="!!virtualClocks[1][1]") {{ virtualClocks[1][1] }}
92 @newmove="processMove"
98 import BaseGame from "@/components/BaseGame.vue";
99 import Chat from "@/components/Chat.vue";
100 import { store } from "@/store";
101 import { GameStorage } from "@/utils/gameStorage";
102 import { ppt } from "@/utils/datetime";
103 import { ajax } from "@/utils/ajax";
104 import { extractTime } from "@/utils/timeControl";
105 import { getRandString } from "@/utils/alea";
106 import { processModalClick } from "@/utils/modalClick";
107 import { getFullNotation } from "@/utils/notation";
108 import { playMove, getFilteredMove } from "@/utils/playUndo";
109 import { getScoreMessage } from "@/utils/scoring";
110 import { ArrayFun } from "@/utils/array";
111 import params from "@/parameters";
118 // gameRef: to find the game in (potentially remote) storage
123 // rid = remote (socket) ID
128 // Passed to BaseGame
129 players: [{ name: "" }, { name: "" }],
134 virtualClocks: [[0,0], [0,0]], //initialized with true game.clocks
135 vr: null, //"variant rules" object initialized from FEN
137 people: {}, //players + observers
138 onMygames: [], //opponents (or me) on "MyGames" page
139 lastate: undefined, //used if opponent send lastate before game is ready
140 repeat: {}, //detect position repetition
143 roomInitialized: false,
144 // If newmove has wrong index: ask fullgame again:
146 gameIsLoading: false,
147 // If asklastate got no reply, ask again:
149 gotMoveIdx: -1, //last move index received
150 // If newmove got no pingback, send again:
151 opponentGotMove: false,
153 // Related to (killing of) self multi-connects:
159 $route: function(to) {
160 this.gameRef.id = to.params["id"];
161 this.gameRef.rid = to.query["rid"];
165 // NOTE: some redundant code with Hall.vue (mostly related to people array)
166 created: function() {
167 // Always add myself to players' list
168 const my = this.st.user;
169 this.$set(this.people, my.sid, { id: my.id, name: my.name });
170 this.gameRef.id = this.$route.params["id"];
171 // rid = remote ID to find an observed live game,
172 // next = next corr games IDs to navigate faster
173 // (Both might be undefined)
174 this.gameRef.rid = this.$route.query["rid"];
175 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
176 // Initialize connection
177 this.connexionString =
184 encodeURIComponent(this.$route.path);
185 this.conn = new WebSocket(this.connexionString);
186 this.conn.onmessage = this.socketMessageListener;
187 this.conn.onclose = this.socketCloseListener;
188 // Socket init required before loading remote game:
189 const socketInit = callback => {
190 if (!!this.conn && this.conn.readyState == 1)
194 // Socket not ready yet (initial loading)
195 // NOTE: it's important to call callback without arguments,
196 // otherwise first arg is Websocket object and loadGame fails.
197 this.conn.onopen = () => callback();
199 if (!this.gameRef.rid)
200 // Game stored locally or on server
201 this.loadGame(null, () => socketInit(this.roomInit));
203 // Game stored remotely: need socket to retrieve it
204 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
205 // --> It will be given when receiving "fullgame" socket event.
206 socketInit(this.loadGame);
208 mounted: function() {
210 .getElementById("chatWrap")
211 .addEventListener("click", processModalClick);
213 beforeDestroy: function() {
214 this.send("disconnect");
217 roomInit: function() {
218 if (!this.roomInitialized) {
219 // Notify the room only now that I connected, because
220 // messages might be lost otherwise (if game loading is slow)
221 this.send("connect");
222 this.send("pollclients");
223 // We may ask fullgame several times if some moves are lost,
224 // but room should be init only once:
225 this.roomInitialized = true;
228 send: function(code, obj) {
230 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
232 isConnected: function(index) {
233 const player = this.game.players[index];
235 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
236 // Still have to check for name (because of potential multi-accounts
237 // on same browser, although this should be rare...)
238 return (!this.st.user.name || this.st.user.name == player.name);
239 // Try to find a match in people:
243 Object.keys(this.people).some(sid => sid == player.sid)
248 Object.values(this.people).some(p => p.id == player.uid)
252 resetChatColor: function() {
253 // TODO: this is called twice, once on opening an once on closing
254 document.getElementById("chatBtn").classList.remove("somethingnew");
256 processChat: function(chat) {
257 this.send("newchat", { data: chat });
258 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
259 if (this.game.type == "corr" && this.st.user.id > 0)
260 GameStorage.update(this.gameRef.id, { chat: chat });
262 clearChat: function() {
263 // Nothing more to do if game is live (chats not recorded)
264 if (this.game.type == "corr") {
265 if (!!this.game.mycolor)
266 ajax("/chats", "DELETE", {gid: this.game.id});
267 this.$set(this.game, "chats", []);
270 // Notify turn after a new move (to opponent and me on MyGames page)
271 notifyTurn: function(sid) {
272 const player = this.people[sid];
273 const colorIdx = this.game.players.findIndex(
274 p => p.sid == sid || p.uid == player.id);
275 const color = ["w","b"][colorIdx];
276 const movesCount = this.game.moves.length;
278 (color == "w" && movesCount % 2 == 0) ||
279 (color == "b" && movesCount % 2 == 1);
280 this.send("turnchange", { target: sid, yourTurn: yourTurn });
282 showNextGame: function() {
283 // Did I play in current game? If not, add it to nextIds list
284 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
285 this.nextIds.unshift(this.game.id);
286 const nextGid = this.nextIds.pop();
288 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
290 rematch: function() {
291 alert("Unimplemented yet (soon :) )");
292 // TODO: same logic as for draw, but re-click remove rematch offer (toggle)
294 askGameAgain: function() {
295 this.gameIsLoading = true;
296 const doAskGame = () => {
297 if (!this.gameRef.rid)
298 // This is my game: just reload.
301 // Just ask fullgame again (once!), this is much simpler.
302 // If this fails, the user could just reload page :/
304 (function askIfPeerConnected() {
305 if (!!self.people[self.gameRef.rid])
306 self.send("askfullgame", { target: self.gameRef.rid });
307 else setTimeout(askIfPeerConnected, 1000);
311 // Delay of at least 2s between two game requests
312 const now = Date.now();
313 const delay = Math.max(2000 - (now - this.askGameTime), 0);
314 this.askGameTime = now;
315 setTimeout(doAskGame, delay);
317 socketMessageListener: function(msg) {
318 if (!this.conn) return;
319 const data = JSON.parse(msg.data);
322 data.sockIds.forEach(sid => {
323 if (sid != this.st.user.sid)
324 this.send("askidentity", { target: sid });
328 if (!this.people[data.from]) {
329 this.newConnect[data.from] = true; //for self multi-connects tests
330 this.send("askidentity", { target: data.from });
334 this.$delete(this.people, data.from);
337 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
338 // Either me (another tab) or opponent
339 const sid = data.from;
340 if (!this.onMygames.some(s => s == sid))
342 this.onMygames.push(sid);
343 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
346 if (!this.people[sid])
347 this.send("askidentity", { target: sid });
350 ArrayFun.remove(this.onMygames, sid => sid == data.from);
353 // I logged in elsewhere:
355 alert(this.st.tr["New connexion detected: tab now offline"]);
357 case "askidentity": {
358 // Request for identification
360 // Decompose to avoid revealing email
361 name: this.st.user.name,
362 sid: this.st.user.sid,
365 this.send("identity", { data: me, target: data.from });
369 const user = data.data;
370 this.$set(this.people, user.sid, { name: user.name, id: user.id });
371 // If I multi-connect, kill current connexion if no mark (I'm older)
372 if (this.newConnect[user.sid]) {
375 user.id == this.st.user.id &&
376 user.sid != this.st.user.sid &&
377 !this.killed[this.st.user.sid]
379 this.send("killme", { sid: this.st.user.sid });
380 this.killed[this.st.user.sid] = true;
382 delete this.newConnect[user.sid];
384 if (!this.killed[this.st.user.sid]) {
385 // Ask potentially missed last state, if opponent and I play
387 !!this.game.mycolor &&
388 this.game.type == "live" &&
389 this.game.score == "*" &&
390 this.game.players.some(p => p.sid == user.sid)
393 (function askLastate() {
394 self.send("asklastate", { target: user.sid });
397 // Ask until we got a reply (or opponent disconnect):
398 if (!self.gotLastate && !!self.people[user.sid])
409 // Send current (live) game if not asked by any of the players
411 this.game.type == "live" &&
412 this.game.players.every(p => p.sid != data.from[0])
417 players: this.game.players,
419 cadence: this.game.cadence,
420 score: this.game.score,
421 rid: this.st.user.sid //useful in Hall if I'm an observer
423 this.send("game", { data: myGame, target: data.from });
427 const gameToSend = Object.keys(this.game)
430 "id","fen","players","vid","cadence","fenStart","vname",
431 "moves","clocks","initime","score","drawOffer"
435 obj[k] = this.game[k];
440 this.send("fullgame", { data: gameToSend, target: data.from });
443 // Callback "roomInit" to poll clients only after game is loaded
444 this.loadGame(data.data, this.roomInit);
447 // Sending informative last state if I played a move or score != "*"
449 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
450 this.game.score != "*" ||
451 this.drawOffer == "sent"
453 // Send our "last state" informations to opponent
454 const L = this.game.moves.length;
455 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
457 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
458 addTime: L > 0 ? this.game.addTimes[L - 1] : undefined,
459 // Since we played a move (or abort or resign),
460 // only drawOffer=="sent" is possible
461 drawSent: this.drawOffer == "sent",
462 score: this.game.score,
464 initime: this.game.initime[1 - myIdx] //relevant only if I played
466 this.send("lastate", { data: myLastate, target: data.from });
468 this.send("lastate", { data: {nothing: true}, target: data.from });
472 // Got opponent infos about last move
473 this.gotLastate = true;
474 if (!data.data.nothing) {
475 this.lastate = data.data;
476 if (this.game.rendered)
477 // Game is rendered (Board component)
478 this.processLastate();
479 // Else: will be processed when game is ready
484 const movePlus = data.data;
485 const movesCount = this.game.moves.length;
486 if (movePlus.index > movesCount) {
487 // This can only happen if I'm an observer and missed a move.
488 if (this.gotMoveIdx < movePlus.index)
489 this.gotMoveIdx = movePlus.index;
490 if (!this.gameIsLoading) this.askGameAgain();
494 movePlus.index < movesCount ||
495 this.gotMoveIdx >= movePlus.index
497 // Opponent re-send but we already have the move:
498 // (maybe he didn't receive our pingback...)
499 this.send("gotmove", {data: movePlus.index, target: data.from});
501 this.gotMoveIdx = movePlus.index;
502 const receiveMyMove = (movePlus.color == this.game.mycolor);
503 if (!receiveMyMove && !!this.game.mycolor)
504 // Notify opponent that I got the move:
505 this.send("gotmove", {data: movePlus.index, target: data.from});
506 if (movePlus.cancelDrawOffer) {
507 // Opponent refuses draw
509 // NOTE for corr games: drawOffer reset by player in turn
511 this.game.type == "live" &&
512 !!this.game.mycolor &&
515 GameStorage.update(this.gameRef.id, { drawOffer: "" });
518 this.$refs["basegame"].play(movePlus.move, "received", null, true);
522 addTime: movePlus.addTime,
523 receiveMyMove: receiveMyMove
531 this.opponentGotMove = true;
535 const score = data.side == "b" ? "1-0" : "0-1";
536 const side = data.side == "w" ? "White" : "Black";
537 this.gameOver(score, side + " surrender");
540 this.gameOver("?", "Stop");
543 this.gameOver("1/2", data.data);
546 // NOTE: observers don't know who offered draw
547 this.drawOffer = "received";
550 this.newChat = data.data;
551 if (!document.getElementById("modalChat").checked)
552 document.getElementById("chatBtn").classList.add("somethingnew");
556 socketCloseListener: function() {
557 this.conn = new WebSocket(this.connexionString);
558 this.conn.addEventListener("message", this.socketMessageListener);
559 this.conn.addEventListener("close", this.socketCloseListener);
561 // lastate was received, but maybe game wasn't ready yet:
562 processLastate: function() {
563 const data = this.lastate;
564 this.lastate = undefined; //security...
565 const L = this.game.moves.length;
566 if (data.movesCount > L) {
567 // Just got last move from him
568 this.$refs["basegame"].play(
572 {addTime: data.addTime, initime: data.initime}
575 if (data.drawSent) this.drawOffer = "received";
576 if (data.score != "*") {
578 if (this.game.score == "*") this.gameOver(data.score);
581 clickDraw: function() {
582 if (!this.game.mycolor) return; //I'm just spectator
583 if (["received", "threerep"].includes(this.drawOffer)) {
584 if (!confirm(this.st.tr["Accept draw?"])) return;
586 this.drawOffer == "received"
588 : "Three repetitions";
589 this.send("draw", { data: message });
590 this.gameOver("1/2", message);
591 } else if (this.drawOffer == "") {
592 // No effect if drawOffer == "sent"
593 if (this.game.mycolor != this.vr.turn) {
594 alert(this.st.tr["Draw offer only in your turn"]);
597 if (!confirm(this.st.tr["Offer draw?"])) return;
598 this.drawOffer = "sent";
599 this.send("drawoffer");
600 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
603 abortGame: function() {
604 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
605 this.gameOver("?", "Stop");
609 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
611 this.send("resign", { data: this.game.mycolor });
612 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
613 const side = this.game.mycolor == "w" ? "White" : "Black";
614 this.gameOver(score, side + " surrender");
616 // 3 cases for loading a game:
617 // - from indexedDB (running or completed live game I play)
618 // - from server (one correspondance game I play[ed] or not)
619 // - from remote peer (one live game I don't play, finished or not)
620 loadGame: function(game, callback) {
621 const afterRetrieval = async game => {
622 const vModule = await import("@/variants/" + game.vname + ".js");
623 window.V = vModule.VariantRules;
624 this.vr = new V(game.fen);
625 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
626 const tc = extractTime(game.cadence);
627 const myIdx = game.players.findIndex(p => {
628 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
630 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
631 if (!game.chats) game.chats = []; //live games don't have chat history
632 if (gtype == "corr") {
633 if (game.players[0].color == "b") {
634 // Adopt the same convention for live and corr games: [0] = white
635 [game.players[0], game.players[1]] = [
640 // NOTE: clocks in seconds, initime in milliseconds
641 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
642 game.clocks = [tc.mainTime, tc.mainTime];
643 const L = game.moves.length;
644 if (game.score == "*") {
645 // Set clocks + initime
646 game.initime = [0, 0];
648 const gameLastupdate = game.moves[L-1].played;
649 game.initime[L % 2] = gameLastupdate;
652 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
656 // Sort chat messages from newest to oldest
657 game.chats.sort((c1, c2) => {
658 return c2.added - c1.added;
660 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
661 // Did a chat message arrive after my last move?
663 if (L == 1 && myIdx == 0)
664 dtLastMove = game.moves[0].played;
667 // It's now white turn
668 dtLastMove = game.moves[L-1-(1-myIdx)].played;
671 dtLastMove = game.moves[L-1-myIdx].played;
674 if (dtLastMove < game.chats[0].added)
675 document.getElementById("chatBtn").classList.add("somethingnew");
677 // Now that we used idx and played, re-format moves as for live games
678 game.moves = game.moves.map(m => m.squares);
680 if (gtype == "live" && game.clocks[0] < 0) {
682 game.clocks = [tc.mainTime, tc.mainTime];
683 if (game.score == "*") {
684 game.initime[0] = Date.now();
686 // I play in this live game; corr games don't have clocks+initime
687 GameStorage.update(game.id, {
689 initime: game.initime
694 if (!!game.drawOffer) {
695 if (game.drawOffer == "t")
697 this.drawOffer = "threerep";
699 // Draw offered by any of the players:
700 if (myIdx < 0) this.drawOffer = "received";
702 // I play in this game:
704 (game.drawOffer == "w" && myIdx == 0) ||
705 (game.drawOffer == "b" && myIdx == 1)
707 this.drawOffer = "sent";
708 else this.drawOffer = "received";
712 this.repeat = {}; //reset: scan past moves' FEN:
714 let vr_tmp = new V(game.fenStart);
716 game.moves.forEach(m => {
718 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
719 this.repeat[fenIdx] = this.repeat[fenIdx]
720 ? this.repeat[fenIdx] + 1
723 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
724 this.game = Object.assign(
725 // NOTE: assign mycolor here, since BaseGame could also be VS computer
728 increment: tc.increment,
730 // opponent sid not strictly required (or available), but easier
731 // at least oppsid or oppid is available anyway:
732 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
733 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
734 addTimes: [], //used for live games
738 if (this.gameIsLoading)
739 // Re-load game because we missed some moves:
740 // artificially reset BaseGame (required if moves arrived in wrong order)
741 this.$refs["basegame"].re_setVariables();
743 this.$nextTick(() => {
744 this.game.rendered = true;
745 // Did lastate arrive before game was rendered?
746 if (this.lastate) this.processLastate();
748 if (this.gameIsLoading) {
749 this.gameIsLoading = false;
750 if (this.gotMoveIdx >= game.moves.length)
751 // Some moves arrived meanwhile...
754 if (!!callback) callback();
757 afterRetrieval(game);
760 if (this.gameRef.rid) {
761 // Remote live game: forgetting about callback func... (TODO: design)
762 this.send("askfullgame", { target: this.gameRef.rid });
764 // Local or corr game
765 // NOTE: afterRetrieval() is never called if game not found
766 GameStorage.get(this.gameRef.id, afterRetrieval);
769 re_setClocks: function() {
770 if (this.game.moves.length < 2 || this.game.score != "*") {
771 // 1st move not completed yet, or game over: freeze time
772 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
775 const currentTurn = this.vr.turn;
776 const currentMovesCount = this.game.moves.length;
777 const colorIdx = ["w", "b"].indexOf(currentTurn);
779 this.game.clocks[colorIdx] -
780 (Date.now() - this.game.initime[colorIdx]) / 1000;
781 this.virtualClocks = [0, 1].map(i => {
783 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
784 return ppt(this.game.clocks[i] - removeTime).split(':');
786 let clockUpdate = setInterval(() => {
789 this.game.moves.length > currentMovesCount ||
790 this.game.score != "*"
792 clearInterval(clockUpdate);
795 currentTurn == "w" ? "0-1" : "1-0",
802 ppt(Math.max(0, --countdown)).split(':')
806 // Update variables and storage after a move:
807 processMove: function(move, data) {
808 if (!data) data = {};
809 const moveCol = this.vr.turn;
810 const doProcessMove = () => {
811 const colorIdx = ["w", "b"].indexOf(moveCol);
812 const nextIdx = 1 - colorIdx;
813 const origMovescount = this.game.moves.length;
815 this.game.type == "live"
816 ? (data.addTime || 0)
818 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
819 if (this.drawOffer == "received")
822 if (this.game.type == "live" && origMovescount >= 2) {
823 const elapsed = Date.now() - this.game.initime[colorIdx];
824 // elapsed time is measured in milliseconds
825 addTime = this.game.increment - elapsed / 1000;
828 // Update current game object:
829 playMove(move, this.vr);
830 // TODO: notifyTurn: "changeturn" message
831 this.game.moves.push(move);
832 // (add)Time indication: useful in case of lastate infos requested
833 if (this.game.type == "live")
834 this.game.addTimes.push(addTime);
835 this.game.fen = this.vr.getFen();
836 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
837 // In corr games, just reset clock to mainTime:
838 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
839 // data.initime is set only when I receive a "lastate" move from opponent
840 this.game.initime[nextIdx] = data.initime || Date.now();
842 // If repetition detected, consider that a draw offer was received:
843 const fenObj = this.vr.getFenForRepeat();
844 this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1;
845 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
846 else if (this.drawOffer == "threerep") this.drawOffer = "";
847 // Since corr games are stored at only one location, update should be
848 // done only by one player for each move:
849 if (!!this.game.mycolor && !data.receiveMyMove) {
850 // NOTE: 'var' to see that variable outside this block
851 var filtered_move = getFilteredMove(move);
854 !!this.game.mycolor &&
855 !data.receiveMyMove &&
856 (this.game.type == "live" || moveCol == this.game.mycolor)
859 switch (this.drawOffer) {
864 drawCode = this.game.mycolor;
867 drawCode = V.GetOppCol(this.game.mycolor);
870 if (this.game.type == "corr") {
871 GameStorage.update(this.gameRef.id, {
874 squares: filtered_move,
878 // Code "n" for "None" to force reset (otherwise it's ignored)
879 drawOffer: drawCode || "n"
883 const updateStorage = () => {
884 GameStorage.update(this.gameRef.id, {
887 moveIdx: origMovescount,
888 clocks: this.game.clocks,
889 initime: this.game.initime,
893 // The active tab can update storage immediately
894 if (!document.hidden) updateStorage();
895 // Small random delay otherwise
896 else setTimeout(updateStorage, 500 + 1000 * Math.random());
899 // Send move ("newmove" event) to people in the room (if our turn)
900 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
903 index: origMovescount,
904 // color is required to check if this is my move (if several tabs opened)
906 addTime: addTime, //undefined for corr games
907 cancelDrawOffer: this.drawOffer == ""
909 this.opponentGotMove = false;
910 this.send("newmove", {data: sendMove});
911 // If the opponent doesn't reply gotmove soon enough, re-send move:
912 let retrySendmove = setInterval(
914 if (this.opponentGotMove) {
915 clearInterval(retrySendmove);
918 let oppsid = this.game.players[nextIdx].sid;
920 oppsid = Object.keys(this.people).find(
921 sid => this.people[sid].id == this.game.players[nextIdx].uid
924 if (!oppsid || !this.people[oppsid])
925 // Opponent is disconnected: he'll ask last state
926 clearInterval(retrySendmove);
927 else this.send("newmove", {data: sendMove, target: oppsid});
934 this.game.type == "corr" &&
935 moveCol == this.game.mycolor &&
939 // TODO: remplacer cette confirm box par qqch de plus discret
940 // (et de même pour challenge accepté / refusé)
943 this.st.tr["Move played:"] +
945 getFullNotation(move) +
947 this.st.tr["Are you sure?"]
950 this.$refs["basegame"].cancelLastMove();
954 // Let small time to finish drawing current move attempt:
957 else doProcessMove();
959 gameOver: function(score, scoreMsg) {
960 this.game.score = score;
961 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
962 const myIdx = this.game.players.findIndex(p => {
963 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
966 // OK, I play in this game
967 GameStorage.update(this.gameRef.id, {
971 // Notify the score to main Hall. TODO: only one player (currently double send)
972 this.send("result", { gid: this.game.id, score: score });
979 <style lang="sass" scoped>
981 background-color: lightgreen
993 @media screen and (min-width: 768px)
996 @media screen and (max-width: 767px)
1001 display: inline-block
1005 display: inline-block
1007 display: inline-flex
1011 @media screen and (max-width: 767px)
1014 @media screen and (max-width: 767px)
1017 @media screen and (min-width: 768px)
1029 background-color: #edda99
1031 display: inline-block
1040 display: inline-block
1053 animation: blink-animation 2s steps(3, start) infinite
1054 @keyframes blink-animation
1059 display: inline-block
1067 .draw-sent, .draw-sent:hover
1068 background-color: lightyellow
1070 .draw-received, .draw-received:hover
1071 background-color: lightgreen
1073 .draw-threerep, .draw-threerep:hover
1074 background-color: #e4d1fc
1077 background-color: #c5fefe