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];
236 (this.st.user.sid == player.sid || this.st.user.id == player.uid) &&
237 (!this.st.user.name || this.st.user.name == player.name)
241 // Try to find a match in people:
245 Object.keys(this.people).some(sid => sid == player.sid)
250 Object.values(this.people).some(p => p.id == player.uid)
254 resetChatColor: function() {
255 // TODO: this is called twice, once on opening an once on closing
256 document.getElementById("chatBtn").classList.remove("somethingnew");
258 processChat: function(chat) {
259 this.send("newchat", { data: chat });
260 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
261 if (this.game.type == "corr" && this.st.user.id > 0)
262 GameStorage.update(this.gameRef.id, { chat: chat });
264 clearChat: function() {
265 // Nothing more to do if game is live (chats not recorded)
266 if (this.game.type == "corr") {
267 if (!!this.game.mycolor)
268 ajax("/chats", "DELETE", {gid: this.game.id});
269 this.$set(this.game, "chats", []);
272 // Notify turn after a new move (to opponent and me on MyGames page)
273 notifyTurn: function(sid) {
274 const player = this.people[sid];
275 const colorIdx = this.game.players.findIndex(
276 p => p.sid == sid || p.uid == player.id);
277 const color = ["w","b"][colorIdx];
278 const movesCount = this.game.moves.length;
280 (color == "w" && movesCount % 2 == 0) ||
281 (color == "b" && movesCount % 2 == 1);
282 this.send("turnchange", { target: sid, yourTurn: yourTurn });
284 showNextGame: function() {
285 // Did I play in current game? If not, add it to nextIds list
286 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
287 this.nextIds.unshift(this.game.id);
288 const nextGid = this.nextIds.pop();
290 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
292 rematch: function() {
293 alert("Unimplemented yet (soon :) )");
294 // TODO: same logic as for draw, but re-click remove rematch offer (toggle)
296 askGameAgain: function() {
297 this.gameIsLoading = true;
298 const doAskGame = () => {
299 if (!this.gameRef.rid)
300 // This is my game: just reload.
303 // Just ask fullgame again (once!), this is much simpler.
304 // If this fails, the user could just reload page :/
306 (function askIfPeerConnected() {
307 if (!!self.people[self.gameRef.rid])
308 self.send("askfullgame", { target: self.gameRef.rid });
309 else setTimeout(askIfPeerConnected, 1000);
313 // Delay of at least 2s between two game requests
314 const now = Date.now();
315 const delay = Math.max(2000 - (now - this.askGameTime), 0);
316 this.askGameTime = now;
317 setTimeout(doAskGame, delay);
319 socketMessageListener: function(msg) {
320 if (!this.conn) return;
321 const data = JSON.parse(msg.data);
324 data.sockIds.forEach(sid => {
325 if (sid != this.st.user.sid)
326 this.send("askidentity", { target: sid });
330 if (!this.people[data.from]) {
331 this.newConnect[data.from] = true; //for self multi-connects tests
332 this.send("askidentity", { target: data.from });
336 this.$delete(this.people, data.from);
339 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
340 // Either me (another tab) or opponent
341 const sid = data.from;
342 if (!this.onMygames.some(s => s == sid))
344 this.onMygames.push(sid);
345 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
348 if (!this.people[sid])
349 this.send("askidentity", { target: sid });
352 ArrayFun.remove(this.onMygames, sid => sid == data.from);
355 // I logged in elsewhere:
357 alert(this.st.tr["New connexion detected: tab now offline"]);
359 case "askidentity": {
360 // Request for identification
362 // Decompose to avoid revealing email
363 name: this.st.user.name,
364 sid: this.st.user.sid,
367 this.send("identity", { data: me, target: data.from });
371 const user = data.data;
372 this.$set(this.people, user.sid, { name: user.name, id: user.id });
373 // If I multi-connect, kill current connexion if no mark (I'm older)
374 if (this.newConnect[user.sid]) {
377 user.id == this.st.user.id &&
378 user.sid != this.st.user.sid &&
379 !this.killed[this.st.user.sid]
381 this.send("killme", { sid: this.st.user.sid });
382 this.killed[this.st.user.sid] = true;
384 delete this.newConnect[user.sid];
386 if (!this.killed[this.st.user.sid]) {
387 // Ask potentially missed last state, if opponent and I play
389 !!this.game.mycolor &&
390 this.game.type == "live" &&
391 this.game.score == "*" &&
392 this.game.players.some(p => p.sid == user.sid)
395 (function askLastate() {
396 self.send("asklastate", { target: user.sid });
399 // Ask until we got a reply (or opponent disconnect):
400 if (!self.gotLastate && !!self.people[user.sid])
411 // Send current (live) game if not asked by any of the players
413 this.game.type == "live" &&
414 this.game.players.every(p => p.sid != data.from[0])
419 players: this.game.players,
421 cadence: this.game.cadence,
422 score: this.game.score,
423 rid: this.st.user.sid //useful in Hall if I'm an observer
425 this.send("game", { data: myGame, target: data.from });
429 const gameToSend = Object.keys(this.game)
432 "id","fen","players","vid","cadence","fenStart","vname",
433 "moves","clocks","initime","score","drawOffer"
437 obj[k] = this.game[k];
442 this.send("fullgame", { data: gameToSend, target: data.from });
445 // Callback "roomInit" to poll clients only after game is loaded
446 this.loadGame(data.data, this.roomInit);
449 // Sending informative last state if I played a move or score != "*"
451 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
452 this.game.score != "*" ||
453 this.drawOffer == "sent"
455 // Send our "last state" informations to opponent
456 const L = this.game.moves.length;
457 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
459 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
460 addTime: L > 0 ? this.game.addTimes[L - 1] : undefined,
461 // Since we played a move (or abort or resign),
462 // only drawOffer=="sent" is possible
463 drawSent: this.drawOffer == "sent",
464 score: this.game.score,
466 initime: this.game.initime[1 - myIdx] //relevant only if I played
468 this.send("lastate", { data: myLastate, target: data.from });
470 this.send("lastate", { data: {nothing: true}, target: data.from });
474 // Got opponent infos about last move
475 this.gotLastate = true;
476 if (!data.data.nothing) {
477 this.lastate = data.data;
478 if (this.game.rendered)
479 // Game is rendered (Board component)
480 this.processLastate();
481 // Else: will be processed when game is ready
486 const movePlus = data.data;
487 const movesCount = this.game.moves.length;
488 if (movePlus.index > movesCount) {
489 // This can only happen if I'm an observer and missed a move.
490 if (this.gotMoveIdx < movePlus.index)
491 this.gotMoveIdx = movePlus.index;
492 if (!this.gameIsLoading) this.askGameAgain();
496 movePlus.index < movesCount ||
497 this.gotMoveIdx >= movePlus.index
499 // Opponent re-send but we already have the move:
500 // (maybe he didn't receive our pingback...)
501 this.send("gotmove", {data: movePlus.index, target: data.from});
503 this.gotMoveIdx = movePlus.index;
504 const receiveMyMove = (movePlus.color == this.game.mycolor);
505 if (!receiveMyMove && !!this.game.mycolor)
506 // Notify opponent that I got the move:
507 this.send("gotmove", {data: movePlus.index, target: data.from});
508 if (movePlus.cancelDrawOffer) {
509 // Opponent refuses draw
511 // NOTE for corr games: drawOffer reset by player in turn
513 this.game.type == "live" &&
514 !!this.game.mycolor &&
517 GameStorage.update(this.gameRef.id, { drawOffer: "" });
520 this.$refs["basegame"].play(movePlus.move, "received", null, true);
524 addTime: movePlus.addTime,
525 receiveMyMove: receiveMyMove
533 this.opponentGotMove = true;
537 const score = data.side == "b" ? "1-0" : "0-1";
538 const side = data.side == "w" ? "White" : "Black";
539 this.gameOver(score, side + " surrender");
542 this.gameOver("?", "Stop");
545 this.gameOver("1/2", data.data);
548 // NOTE: observers don't know who offered draw
549 this.drawOffer = "received";
552 this.newChat = data.data;
553 if (!document.getElementById("modalChat").checked)
554 document.getElementById("chatBtn").classList.add("somethingnew");
558 socketCloseListener: function() {
559 this.conn = new WebSocket(this.connexionString);
560 this.conn.addEventListener("message", this.socketMessageListener);
561 this.conn.addEventListener("close", this.socketCloseListener);
563 // lastate was received, but maybe game wasn't ready yet:
564 processLastate: function() {
565 const data = this.lastate;
566 this.lastate = undefined; //security...
567 const L = this.game.moves.length;
568 if (data.movesCount > L) {
569 // Just got last move from him
570 this.$refs["basegame"].play(
574 {addTime: data.addTime, initime: data.initime}
577 if (data.drawSent) this.drawOffer = "received";
578 if (data.score != "*") {
580 if (this.game.score == "*") this.gameOver(data.score);
583 clickDraw: function() {
584 if (!this.game.mycolor) return; //I'm just spectator
585 if (["received", "threerep"].includes(this.drawOffer)) {
586 if (!confirm(this.st.tr["Accept draw?"])) return;
588 this.drawOffer == "received"
590 : "Three repetitions";
591 this.send("draw", { data: message });
592 this.gameOver("1/2", message);
593 } else if (this.drawOffer == "") {
594 // No effect if drawOffer == "sent"
595 if (this.game.mycolor != this.vr.turn) {
596 alert(this.st.tr["Draw offer only in your turn"]);
599 if (!confirm(this.st.tr["Offer draw?"])) return;
600 this.drawOffer = "sent";
601 this.send("drawoffer");
602 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
605 abortGame: function() {
606 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
607 this.gameOver("?", "Stop");
611 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
613 this.send("resign", { data: this.game.mycolor });
614 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
615 const side = this.game.mycolor == "w" ? "White" : "Black";
616 this.gameOver(score, side + " surrender");
618 // 3 cases for loading a game:
619 // - from indexedDB (running or completed live game I play)
620 // - from server (one correspondance game I play[ed] or not)
621 // - from remote peer (one live game I don't play, finished or not)
622 loadGame: function(game, callback) {
623 const afterRetrieval = async game => {
624 const vModule = await import("@/variants/" + game.vname + ".js");
625 window.V = vModule.VariantRules;
626 this.vr = new V(game.fen);
627 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
628 const tc = extractTime(game.cadence);
629 const myIdx = game.players.findIndex(p => {
630 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
632 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
633 if (!game.chats) game.chats = []; //live games don't have chat history
634 if (gtype == "corr") {
635 if (game.players[0].color == "b") {
636 // Adopt the same convention for live and corr games: [0] = white
637 [game.players[0], game.players[1]] = [
642 // NOTE: clocks in seconds, initime in milliseconds
643 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
644 game.clocks = [tc.mainTime, tc.mainTime];
645 const L = game.moves.length;
646 if (game.score == "*") {
647 // Set clocks + initime
648 game.initime = [0, 0];
650 const gameLastupdate = game.moves[L-1].played;
651 game.initime[L % 2] = gameLastupdate;
654 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
658 // Sort chat messages from newest to oldest
659 game.chats.sort((c1, c2) => {
660 return c2.added - c1.added;
662 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
663 // Did a chat message arrive after my last move?
665 if (L == 1 && myIdx == 0)
666 dtLastMove = game.moves[0].played;
669 // It's now white turn
670 dtLastMove = game.moves[L-1-(1-myIdx)].played;
673 dtLastMove = game.moves[L-1-myIdx].played;
676 if (dtLastMove < game.chats[0].added)
677 document.getElementById("chatBtn").classList.add("somethingnew");
679 // Now that we used idx and played, re-format moves as for live games
680 game.moves = game.moves.map(m => m.squares);
682 if (gtype == "live" && game.clocks[0] < 0) {
684 game.clocks = [tc.mainTime, tc.mainTime];
685 if (game.score == "*") {
686 game.initime[0] = Date.now();
688 // I play in this live game; corr games don't have clocks+initime
689 GameStorage.update(game.id, {
691 initime: game.initime
696 if (!!game.drawOffer) {
697 if (game.drawOffer == "t")
699 this.drawOffer = "threerep";
701 // Draw offered by any of the players:
702 if (myIdx < 0) this.drawOffer = "received";
704 // I play in this game:
706 (game.drawOffer == "w" && myIdx == 0) ||
707 (game.drawOffer == "b" && myIdx == 1)
709 this.drawOffer = "sent";
710 else this.drawOffer = "received";
714 this.repeat = {}; //reset: scan past moves' FEN:
716 let vr_tmp = new V(game.fenStart);
718 game.moves.forEach(m => {
720 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
721 this.repeat[fenIdx] = this.repeat[fenIdx]
722 ? this.repeat[fenIdx] + 1
725 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
726 this.game = Object.assign(
727 // NOTE: assign mycolor here, since BaseGame could also be VS computer
730 increment: tc.increment,
732 // opponent sid not strictly required (or available), but easier
733 // at least oppsid or oppid is available anyway:
734 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
735 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
736 addTimes: [], //used for live games
740 if (this.gameIsLoading)
741 // Re-load game because we missed some moves:
742 // artificially reset BaseGame (required if moves arrived in wrong order)
743 this.$refs["basegame"].re_setVariables();
745 this.$nextTick(() => {
746 this.game.rendered = true;
747 // Did lastate arrive before game was rendered?
748 if (this.lastate) this.processLastate();
750 if (this.gameIsLoading) {
751 this.gameIsLoading = false;
752 if (this.gotMoveIdx >= game.moves.length)
753 // Some moves arrived meanwhile...
756 if (!!callback) callback();
759 afterRetrieval(game);
762 if (this.gameRef.rid) {
763 // Remote live game: forgetting about callback func... (TODO: design)
764 this.send("askfullgame", { target: this.gameRef.rid });
766 // Local or corr game
767 // NOTE: afterRetrieval() is never called if game not found
768 GameStorage.get(this.gameRef.id, afterRetrieval);
771 re_setClocks: function() {
772 if (this.game.moves.length < 2 || this.game.score != "*") {
773 // 1st move not completed yet, or game over: freeze time
774 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
777 const currentTurn = this.vr.turn;
778 const currentMovesCount = this.game.moves.length;
779 const colorIdx = ["w", "b"].indexOf(currentTurn);
781 this.game.clocks[colorIdx] -
782 (Date.now() - this.game.initime[colorIdx]) / 1000;
783 this.virtualClocks = [0, 1].map(i => {
785 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
786 return ppt(this.game.clocks[i] - removeTime).split(':');
788 let clockUpdate = setInterval(() => {
791 this.game.moves.length > currentMovesCount ||
792 this.game.score != "*"
794 clearInterval(clockUpdate);
797 currentTurn == "w" ? "0-1" : "1-0",
804 ppt(Math.max(0, --countdown)).split(':')
808 // Update variables and storage after a move:
809 processMove: function(move, data) {
810 if (!data) data = {};
811 const moveCol = this.vr.turn;
812 const doProcessMove = () => {
813 const colorIdx = ["w", "b"].indexOf(moveCol);
814 const nextIdx = 1 - colorIdx;
815 const origMovescount = this.game.moves.length;
817 this.game.type == "live"
818 ? (data.addTime || 0)
820 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
821 if (this.drawOffer == "received")
824 if (this.game.type == "live" && origMovescount >= 2) {
825 const elapsed = Date.now() - this.game.initime[colorIdx];
826 // elapsed time is measured in milliseconds
827 addTime = this.game.increment - elapsed / 1000;
830 // Update current game object:
831 playMove(move, this.vr);
832 // TODO: notifyTurn: "changeturn" message
833 this.game.moves.push(move);
834 // (add)Time indication: useful in case of lastate infos requested
835 if (this.game.type == "live")
836 this.game.addTimes.push(addTime);
837 this.game.fen = this.vr.getFen();
838 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
839 // In corr games, just reset clock to mainTime:
840 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
841 // data.initime is set only when I receive a "lastate" move from opponent
842 this.game.initime[nextIdx] = data.initime || Date.now();
844 // If repetition detected, consider that a draw offer was received:
845 const fenObj = this.vr.getFenForRepeat();
846 this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1;
847 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
848 else if (this.drawOffer == "threerep") this.drawOffer = "";
849 // Since corr games are stored at only one location, update should be
850 // done only by one player for each move:
851 if (!!this.game.mycolor && !data.receiveMyMove) {
852 // NOTE: 'var' to see that variable outside this block
853 var filtered_move = getFilteredMove(move);
856 !!this.game.mycolor &&
857 !data.receiveMyMove &&
858 (this.game.type == "live" || moveCol == this.game.mycolor)
861 switch (this.drawOffer) {
866 drawCode = this.game.mycolor;
869 drawCode = V.GetOppCol(this.game.mycolor);
872 if (this.game.type == "corr") {
873 GameStorage.update(this.gameRef.id, {
876 squares: filtered_move,
880 // Code "n" for "None" to force reset (otherwise it's ignored)
881 drawOffer: drawCode || "n"
885 const updateStorage = () => {
886 GameStorage.update(this.gameRef.id, {
889 moveIdx: origMovescount,
890 clocks: this.game.clocks,
891 initime: this.game.initime,
895 // The active tab can update storage immediately
896 if (!document.hidden) updateStorage();
897 // Small random delay otherwise
898 else setTimeout(updateStorage, 500 + 1000 * Math.random());
901 // Send move ("newmove" event) to people in the room (if our turn)
902 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
905 index: origMovescount,
906 // color is required to check if this is my move (if several tabs opened)
908 addTime: addTime, //undefined for corr games
909 cancelDrawOffer: this.drawOffer == ""
911 this.opponentGotMove = false;
912 this.send("newmove", {data: sendMove});
913 // If the opponent doesn't reply gotmove soon enough, re-send move:
914 let retrySendmove = setInterval(
916 if (this.opponentGotMove) {
917 clearInterval(retrySendmove);
920 let oppsid = this.game.players[nextIdx].sid;
922 oppsid = Object.keys(this.people).find(
923 sid => this.people[sid].id == this.game.players[nextIdx].uid
926 if (!oppsid || !this.people[oppsid])
927 // Opponent is disconnected: he'll ask last state
928 clearInterval(retrySendmove);
929 else this.send("newmove", {data: sendMove, target: oppsid});
936 this.game.type == "corr" &&
937 moveCol == this.game.mycolor &&
941 // TODO: remplacer cette confirm box par qqch de plus discret
942 // (et de même pour challenge accepté / refusé)
945 this.st.tr["Move played:"] +
947 getFullNotation(move) +
949 this.st.tr["Are you sure?"]
952 this.$refs["basegame"].cancelLastMove();
956 // Let small time to finish drawing current move attempt:
959 else doProcessMove();
961 gameOver: function(score, scoreMsg) {
962 this.game.score = score;
963 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
964 const myIdx = this.game.players.findIndex(p => {
965 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
968 // OK, I play in this game
969 GameStorage.update(this.gameRef.id, {
973 // Notify the score to main Hall. TODO: only one player (currently double send)
974 this.send("result", { gid: this.game.id, score: score });
981 <style lang="sass" scoped>
983 background-color: lightgreen
995 @media screen and (min-width: 768px)
998 @media screen and (max-width: 767px)
1003 display: inline-block
1007 display: inline-block
1009 display: inline-flex
1013 @media screen and (max-width: 767px)
1016 @media screen and (max-width: 767px)
1019 @media screen and (min-width: 768px)
1031 background-color: #edda99
1033 display: inline-block
1042 display: inline-block
1055 animation: blink-animation 2s steps(3, start) infinite
1056 @keyframes blink-animation
1061 display: inline-block
1069 .draw-sent, .draw-sent:hover
1070 background-color: lightyellow
1072 .draw-received, .draw-received:hover
1073 background-color: lightgreen
1075 .draw-threerep, .draw-threerep:hover
1076 background-color: #e4d1fc
1079 background-color: #c5fefe