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)
237 // Try to find a match in people:
241 Object.keys(this.people).some(sid => sid == player.sid)
246 Object.values(this.people).some(p => p.id == player.uid)
250 resetChatColor: function() {
251 // TODO: this is called twice, once on opening an once on closing
252 document.getElementById("chatBtn").classList.remove("somethingnew");
254 processChat: function(chat) {
255 this.send("newchat", { data: chat });
256 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
257 if (this.game.type == "corr" && this.st.user.id > 0)
258 GameStorage.update(this.gameRef.id, { chat: chat });
260 clearChat: function() {
261 // Nothing more to do if game is live (chats not recorded)
262 if (this.game.type == "corr") {
263 if (!!this.game.mycolor)
264 ajax("/chats", "DELETE", {gid: this.game.id});
265 this.$set(this.game, "chats", []);
268 // Notify turn after a new move (to opponent and me on MyGames page)
269 notifyTurn: function(sid) {
270 const player = this.people[sid];
271 const colorIdx = this.game.players.findIndex(
272 p => p.sid == sid || p.uid == player.id);
273 const color = ["w","b"][colorIdx];
274 const movesCount = this.game.moves.length;
276 (color == "w" && movesCount % 2 == 0) ||
277 (color == "b" && movesCount % 2 == 1);
278 this.send("turnchange", { target: sid, yourTurn: yourTurn });
280 showNextGame: function() {
281 // Did I play in current game? If not, add it to nextIds list
282 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
283 this.nextIds.unshift(this.game.id);
284 const nextGid = this.nextIds.pop();
286 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
288 rematch: function() {
289 alert("Unimplemented yet (soon :) )");
290 // TODO: same logic as for draw, but re-click remove rematch offer (toggle)
292 askGameAgain: function() {
293 this.gameIsLoading = true;
294 const doAskGame = () => {
295 if (!this.gameRef.rid)
296 // This is my game: just reload.
299 // Just ask fullgame again (once!), this is much simpler.
300 // If this fails, the user could just reload page :/
302 (function askIfPeerConnected() {
303 if (!!self.people[self.gameRef.rid])
304 self.send("askfullgame", { target: self.gameRef.rid });
305 else setTimeout(askIfPeerConnected, 1000);
309 // Delay of at least 2s between two game requests
310 const now = Date.now();
311 const delay = Math.max(2000 - (now - this.askGameTime), 0);
312 this.askGameTime = now;
313 setTimeout(doAskGame, delay);
315 socketMessageListener: function(msg) {
316 if (!this.conn) return;
317 const data = JSON.parse(msg.data);
320 data.sockIds.forEach(sid => {
321 if (sid != this.st.user.sid)
322 this.send("askidentity", { target: sid });
326 if (!this.people[data.from]) {
327 this.newConnect[data.from] = true; //for self multi-connects tests
328 this.send("askidentity", { target: data.from });
332 this.$delete(this.people, data.from);
335 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
336 // Either me (another tab) or opponent
337 const sid = data.from;
338 if (!this.onMygames.some(s => s == sid))
340 this.onMygames.push(sid);
341 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
344 if (!this.people[sid])
345 this.send("askidentity", { target: sid });
348 ArrayFun.remove(this.onMygames, sid => sid == data.from);
351 // I logged in elsewhere:
353 alert(this.st.tr["New connexion detected: tab now offline"]);
355 case "askidentity": {
356 // Request for identification
358 // Decompose to avoid revealing email
359 name: this.st.user.name,
360 sid: this.st.user.sid,
363 this.send("identity", { data: me, target: data.from });
367 const user = data.data;
368 this.$set(this.people, user.sid, { name: user.name, id: user.id });
369 // If I multi-connect, kill current connexion if no mark (I'm older)
370 if (this.newConnect[user.sid]) {
373 user.id == this.st.user.id &&
374 user.sid != this.st.user.sid &&
375 !this.killed[this.st.user.sid]
377 this.send("killme", { sid: this.st.user.sid });
378 this.killed[this.st.user.sid] = true;
380 delete this.newConnect[user.sid];
382 if (!this.killed[this.st.user.sid]) {
383 // Ask potentially missed last state, if opponent and I play
385 !!this.game.mycolor &&
386 this.game.type == "live" &&
387 this.game.score == "*" &&
388 this.game.players.some(p => p.sid == user.sid)
391 (function askLastate() {
392 self.send("asklastate", { target: user.sid });
395 // Ask until we got a reply (or opponent disconnect):
396 if (!self.gotLastate && !!self.people[user.sid])
407 // Send current (live) game if not asked by any of the players
409 this.game.type == "live" &&
410 this.game.players.every(p => p.sid != data.from[0])
415 players: this.game.players,
417 cadence: this.game.cadence,
418 score: this.game.score,
419 rid: this.st.user.sid //useful in Hall if I'm an observer
421 this.send("game", { data: myGame, target: data.from });
425 const gameToSend = Object.keys(this.game)
428 "id","fen","players","vid","cadence","fenStart","vname",
429 "moves","clocks","initime","score","drawOffer"
433 obj[k] = this.game[k];
438 this.send("fullgame", { data: gameToSend, target: data.from });
441 // Callback "roomInit" to poll clients only after game is loaded
442 this.loadGame(data.data, this.roomInit);
445 // Sending informative last state if I played a move or score != "*"
447 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
448 this.game.score != "*" ||
449 this.drawOffer == "sent"
451 // Send our "last state" informations to opponent
452 const L = this.game.moves.length;
453 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
455 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
456 addTime: L > 0 ? this.game.addTimes[L - 1] : undefined,
457 // Since we played a move (or abort or resign),
458 // only drawOffer=="sent" is possible
459 drawSent: this.drawOffer == "sent",
460 score: this.game.score,
462 initime: this.game.initime[1 - myIdx] //relevant only if I played
464 this.send("lastate", { data: myLastate, target: data.from });
466 this.send("lastate", { data: {nothing: true}, target: data.from });
470 // Got opponent infos about last move
471 this.gotLastate = true;
472 if (!data.data.nothing) {
473 this.lastate = data.data;
474 if (this.game.rendered)
475 // Game is rendered (Board component)
476 this.processLastate();
477 // Else: will be processed when game is ready
482 const movePlus = data.data;
483 const movesCount = this.game.moves.length;
484 if (movePlus.index > movesCount) {
485 // This can only happen if I'm an observer and missed a move.
486 if (this.gotMoveIdx < movePlus.index)
487 this.gotMoveIdx = movePlus.index;
488 if (!this.gameIsLoading) this.askGameAgain();
492 movePlus.index < movesCount ||
493 this.gotMoveIdx >= movePlus.index
495 // Opponent re-send but we already have the move:
496 // (maybe he didn't receive our pingback...)
497 this.send("gotmove", {data: movePlus.index, target: data.from});
499 this.gotMoveIdx = movePlus.index;
500 const receiveMyMove = (movePlus.color == this.game.mycolor);
501 if (!receiveMyMove && !!this.game.mycolor)
502 // Notify opponent that I got the move:
503 this.send("gotmove", {data: movePlus.index, target: data.from});
504 if (movePlus.cancelDrawOffer) {
505 // Opponent refuses draw
507 // NOTE for corr games: drawOffer reset by player in turn
509 this.game.type == "live" &&
510 !!this.game.mycolor &&
513 GameStorage.update(this.gameRef.id, { drawOffer: "" });
516 this.$refs["basegame"].play(movePlus.move, "received", null, true);
520 addTime: movePlus.addTime,
521 receiveMyMove: receiveMyMove
529 this.opponentGotMove = true;
533 const score = data.side == "b" ? "1-0" : "0-1";
534 const side = data.side == "w" ? "White" : "Black";
535 this.gameOver(score, side + " surrender");
538 this.gameOver("?", "Stop");
541 this.gameOver("1/2", data.data);
544 // NOTE: observers don't know who offered draw
545 this.drawOffer = "received";
548 this.newChat = data.data;
549 if (!document.getElementById("modalChat").checked)
550 document.getElementById("chatBtn").classList.add("somethingnew");
554 socketCloseListener: function() {
555 this.conn = new WebSocket(this.connexionString);
556 this.conn.addEventListener("message", this.socketMessageListener);
557 this.conn.addEventListener("close", this.socketCloseListener);
559 // lastate was received, but maybe game wasn't ready yet:
560 processLastate: function() {
561 const data = this.lastate;
562 this.lastate = undefined; //security...
563 const L = this.game.moves.length;
564 if (data.movesCount > L) {
565 // Just got last move from him
566 this.$refs["basegame"].play(
570 {addTime: data.addTime, initime: data.initime}
573 if (data.drawSent) this.drawOffer = "received";
574 if (data.score != "*") {
576 if (this.game.score == "*") this.gameOver(data.score);
579 clickDraw: function() {
580 if (!this.game.mycolor) return; //I'm just spectator
581 if (["received", "threerep"].includes(this.drawOffer)) {
582 if (!confirm(this.st.tr["Accept draw?"])) return;
584 this.drawOffer == "received"
586 : "Three repetitions";
587 this.send("draw", { data: message });
588 this.gameOver("1/2", message);
589 } else if (this.drawOffer == "") {
590 // No effect if drawOffer == "sent"
591 if (this.game.mycolor != this.vr.turn) {
592 alert(this.st.tr["Draw offer only in your turn"]);
595 if (!confirm(this.st.tr["Offer draw?"])) return;
596 this.drawOffer = "sent";
597 this.send("drawoffer");
598 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
601 abortGame: function() {
602 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
603 this.gameOver("?", "Stop");
607 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
609 this.send("resign", { data: this.game.mycolor });
610 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
611 const side = this.game.mycolor == "w" ? "White" : "Black";
612 this.gameOver(score, side + " surrender");
614 // 3 cases for loading a game:
615 // - from indexedDB (running or completed live game I play)
616 // - from server (one correspondance game I play[ed] or not)
617 // - from remote peer (one live game I don't play, finished or not)
618 loadGame: function(game, callback) {
619 const afterRetrieval = async game => {
620 const vModule = await import("@/variants/" + game.vname + ".js");
621 window.V = vModule.VariantRules;
622 this.vr = new V(game.fen);
623 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
624 const tc = extractTime(game.cadence);
625 const myIdx = game.players.findIndex(p => {
626 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
628 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
629 if (!game.chats) game.chats = []; //live games don't have chat history
630 if (gtype == "corr") {
631 if (game.players[0].color == "b") {
632 // Adopt the same convention for live and corr games: [0] = white
633 [game.players[0], game.players[1]] = [
638 // NOTE: clocks in seconds, initime in milliseconds
639 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
640 game.clocks = [tc.mainTime, tc.mainTime];
641 const L = game.moves.length;
642 if (game.score == "*") {
643 // Set clocks + initime
644 game.initime = [0, 0];
646 const gameLastupdate = game.moves[L-1].played;
647 game.initime[L % 2] = gameLastupdate;
650 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
654 // Sort chat messages from newest to oldest
655 game.chats.sort((c1, c2) => {
656 return c2.added - c1.added;
658 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
659 // Did a chat message arrive after my last move?
661 if (L == 1 && myIdx == 0)
662 dtLastMove = game.moves[0].played;
665 // It's now white turn
666 dtLastMove = game.moves[L-1-(1-myIdx)].played;
669 dtLastMove = game.moves[L-1-myIdx].played;
672 if (dtLastMove < game.chats[0].added)
673 document.getElementById("chatBtn").classList.add("somethingnew");
675 // Now that we used idx and played, re-format moves as for live games
676 game.moves = game.moves.map(m => m.squares);
678 if (gtype == "live" && game.clocks[0] < 0) {
680 game.clocks = [tc.mainTime, tc.mainTime];
681 if (game.score == "*") {
682 game.initime[0] = Date.now();
684 // I play in this live game; corr games don't have clocks+initime
685 GameStorage.update(game.id, {
687 initime: game.initime
692 if (!!game.drawOffer) {
693 if (game.drawOffer == "t")
695 this.drawOffer = "threerep";
697 // Draw offered by any of the players:
698 if (myIdx < 0) this.drawOffer = "received";
700 // I play in this game:
702 (game.drawOffer == "w" && myIdx == 0) ||
703 (game.drawOffer == "b" && myIdx == 1)
705 this.drawOffer = "sent";
706 else this.drawOffer = "received";
710 this.repeat = {}; //reset: scan past moves' FEN:
712 let vr_tmp = new V(game.fenStart);
714 game.moves.forEach(m => {
716 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
717 this.repeat[fenIdx] = this.repeat[fenIdx]
718 ? this.repeat[fenIdx] + 1
721 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
722 this.game = Object.assign(
723 // NOTE: assign mycolor here, since BaseGame could also be VS computer
726 increment: tc.increment,
728 // opponent sid not strictly required (or available), but easier
729 // at least oppsid or oppid is available anyway:
730 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
731 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
732 addTimes: [], //used for live games
736 if (this.gameIsLoading)
737 // Re-load game because we missed some moves:
738 // artificially reset BaseGame (required if moves arrived in wrong order)
739 this.$refs["basegame"].re_setVariables();
741 this.$nextTick(() => {
742 this.game.rendered = true;
743 // Did lastate arrive before game was rendered?
744 if (this.lastate) this.processLastate();
746 if (this.gameIsLoading) {
747 this.gameIsLoading = false;
748 if (this.gotMoveIdx >= game.moves.length)
749 // Some moves arrived meanwhile...
752 if (!!callback) callback();
755 afterRetrieval(game);
758 if (this.gameRef.rid) {
759 // Remote live game: forgetting about callback func... (TODO: design)
760 this.send("askfullgame", { target: this.gameRef.rid });
762 // Local or corr game
763 // NOTE: afterRetrieval() is never called if game not found
764 GameStorage.get(this.gameRef.id, afterRetrieval);
767 re_setClocks: function() {
768 if (this.game.moves.length < 2 || this.game.score != "*") {
769 // 1st move not completed yet, or game over: freeze time
770 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
773 const currentTurn = this.vr.turn;
774 const currentMovesCount = this.game.moves.length;
775 const colorIdx = ["w", "b"].indexOf(currentTurn);
777 this.game.clocks[colorIdx] -
778 (Date.now() - this.game.initime[colorIdx]) / 1000;
779 this.virtualClocks = [0, 1].map(i => {
781 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
782 return ppt(this.game.clocks[i] - removeTime).split(':');
784 let clockUpdate = setInterval(() => {
787 this.game.moves.length > currentMovesCount ||
788 this.game.score != "*"
790 clearInterval(clockUpdate);
793 currentTurn == "w" ? "0-1" : "1-0",
800 ppt(Math.max(0, --countdown)).split(':')
804 // Update variables and storage after a move:
805 processMove: function(move, data) {
806 if (!data) data = {};
807 const moveCol = this.vr.turn;
808 const doProcessMove = () => {
809 const colorIdx = ["w", "b"].indexOf(moveCol);
810 const nextIdx = 1 - colorIdx;
811 const origMovescount = this.game.moves.length;
813 this.game.type == "live"
814 ? (data.addTime || 0)
816 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
817 if (this.drawOffer == "received")
820 if (this.game.type == "live" && origMovescount >= 2) {
821 const elapsed = Date.now() - this.game.initime[colorIdx];
822 // elapsed time is measured in milliseconds
823 addTime = this.game.increment - elapsed / 1000;
826 // Update current game object:
827 playMove(move, this.vr);
828 // TODO: notifyTurn: "changeturn" message
829 this.game.moves.push(move);
830 // (add)Time indication: useful in case of lastate infos requested
831 if (this.game.type == "live")
832 this.game.addTimes.push(addTime);
833 this.game.fen = this.vr.getFen();
834 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
835 // In corr games, just reset clock to mainTime:
836 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
837 // data.initime is set only when I receive a "lastate" move from opponent
838 this.game.initime[nextIdx] = data.initime || Date.now();
840 // If repetition detected, consider that a draw offer was received:
841 const fenObj = this.vr.getFenForRepeat();
842 this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1;
843 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
844 else if (this.drawOffer == "threerep") this.drawOffer = "";
845 // Since corr games are stored at only one location, update should be
846 // done only by one player for each move:
847 if (!!this.game.mycolor && !data.receiveMyMove) {
848 // NOTE: 'var' to see that variable outside this block
849 var filtered_move = getFilteredMove(move);
852 !!this.game.mycolor &&
853 !data.receiveMyMove &&
854 (this.game.type == "live" || moveCol == this.game.mycolor)
857 switch (this.drawOffer) {
862 drawCode = this.game.mycolor;
865 drawCode = V.GetOppCol(this.game.mycolor);
868 if (this.game.type == "corr") {
869 GameStorage.update(this.gameRef.id, {
872 squares: filtered_move,
876 // Code "n" for "None" to force reset (otherwise it's ignored)
877 drawOffer: drawCode || "n"
881 const updateStorage = () => {
882 GameStorage.update(this.gameRef.id, {
885 moveIdx: origMovescount,
886 clocks: this.game.clocks,
887 initime: this.game.initime,
891 // The active tab can update storage immediately
892 if (!document.hidden) updateStorage();
893 // Small random delay otherwise
894 else setTimeout(updateStorage, 500 + 1000 * Math.random());
897 // Send move ("newmove" event) to people in the room (if our turn)
898 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
901 index: origMovescount,
902 // color is required to check if this is my move (if several tabs opened)
904 addTime: addTime, //undefined for corr games
905 cancelDrawOffer: this.drawOffer == ""
907 this.opponentGotMove = false;
908 this.send("newmove", {data: sendMove});
909 // If the opponent doesn't reply gotmove soon enough, re-send move:
910 let retrySendmove = setInterval(
912 if (this.opponentGotMove) {
913 clearInterval(retrySendmove);
916 let oppsid = this.game.players[nextIdx].sid;
918 oppsid = Object.keys(this.people).find(
919 sid => this.people[sid].id == this.game.players[nextIdx].uid
922 if (!oppsid || !this.people[oppsid])
923 // Opponent is disconnected: he'll ask last state
924 clearInterval(retrySendmove);
925 else this.send("newmove", {data: sendMove, target: oppsid});
932 this.game.type == "corr" &&
933 moveCol == this.game.mycolor &&
937 // TODO: remplacer cette confirm box par qqch de plus discret
938 // (et de même pour challenge accepté / refusé)
941 this.st.tr["Move played:"] +
943 getFullNotation(move) +
945 this.st.tr["Are you sure?"]
948 this.$refs["basegame"].cancelLastMove();
952 // Let small time to finish drawing current move attempt:
955 else doProcessMove();
957 gameOver: function(score, scoreMsg) {
958 this.game.score = score;
959 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
960 const myIdx = this.game.players.findIndex(p => {
961 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
964 // OK, I play in this game
965 GameStorage.update(this.gameRef.id, {
969 // Notify the score to main Hall. TODO: only one player (currently double send)
970 this.send("result", { gid: this.game.id, score: score });
977 <style lang="sass" scoped>
979 background-color: lightgreen
991 @media screen and (min-width: 768px)
994 @media screen and (max-width: 767px)
999 display: inline-block
1003 display: inline-block
1005 display: inline-flex
1009 @media screen and (max-width: 767px)
1012 @media screen and (max-width: 767px)
1015 @media screen and (min-width: 768px)
1027 background-color: #edda99
1029 display: inline-block
1038 display: inline-block
1051 animation: blink-animation 2s steps(3, start) infinite
1052 @keyframes blink-animation
1057 display: inline-block
1065 .draw-sent, .draw-sent:hover
1066 background-color: lightyellow
1068 .draw-received, .draw-received:hover
1069 background-color: lightgreen
1071 .draw-threerep, .draw-threerep:hover
1072 background-color: #e4d1fc
1075 background-color: #c5fefe