3 input#modalRules.modal(type="checkbox")
6 data-checkbox="modalRules"
9 label.modal-close(for="modalRules")
10 a#variantNameInGame(:href="'/#/variants/'+game.vname") {{ game.vdisp }}
11 div(v-html="rulesContent")
12 input#modalScore.modal(type="checkbox")
15 data-checkbox="modalScore"
18 label.modal-close(for="modalScore")
20 span.score {{ game.score }}
22 span.score-msg {{ st.tr[game.scoreMsg] }}
23 input#modalRematch.modal(type="checkbox")
26 data-checkbox="modalRematch"
29 label.modal-close(for="modalRematch")
31 :href="'#/game/' + rematchId"
32 onClick="document.getElementById('modalRematch').checked=false"
34 | {{ st.tr["Rematch in progress"] }}
35 input#modalChat.modal(
41 data-checkbox="modalChat"
44 label.modal-close(for="modalChat")
46 span {{ st.tr["Participant(s):"] }}
48 v-for="p in Object.values(people)"
52 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
55 :players="game.players"
56 :pastChats="game.chats"
58 @chatcleared="clearChat"
60 input#modalConfirm.modal(type="checkbox")
61 div#confirmDiv(role="dialog")
64 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
68 span {{ st.tr["Move played:"] + " " }}
69 span.bold {{ moveNotation }}
71 span {{ st.tr["Are you sure?"] }}
72 .button-group#buttonsConfirm
73 // onClick for acceptBtn: set dynamically
75 span {{ st.tr["Validate"] }}
76 button.refuseBtn(@click="cancelMove()")
77 span {{ st.tr["Cancel"] }}
80 span.variant-cadence(v-if="game.type!='import'") {{ game.cadence }}
83 | {{ !!vr ? vr.constructor.AbbreviateOptions(game.options) : '' }}
85 v-if="nextIds.length > 0"
86 @click="showNextGame()"
88 | {{ st.tr["Next_g"] }}
90 :class="btnTooltipClass()"
91 onClick="window.doClick('modalChat')"
94 img(src="/images/icons/chat.svg")
95 #actions(v-if="game.score=='*'")
98 :class="btnTooltipClass('draw')"
99 :aria-label="st.tr['Draw']"
101 img(src="/images/icons/draw.svg")
103 v-if="!!game.mycolor"
104 :class="btnTooltipClass()"
106 :aria-label="st.tr['Abort']"
108 img(src="/images/icons/abort.svg")
110 v-if="!!game.mycolor"
111 :class="btnTooltipClass()"
113 :aria-label="st.tr['Resign']"
115 img(src="/images/icons/resign.svg")
118 :class="btnTooltipClass('rematch')"
119 @click="clickRematch()"
120 :aria-label="st.tr['Rematch']"
122 img(src="/images/icons/rematch.svg")
124 div(v-if="isLargeScreen()")
126 :class="{connected: isConnected(0)}"
127 :uid="game.players[0].id"
128 :uname="game.players[0].name"
131 v-if="game.score=='*'"
132 :class="{yourturn: !!vr && vr.turn == 'w'}"
134 span.time-left {{ virtualClocks[0][0] }}
135 span.time-separator(v-if="!!virtualClocks[0][1]") :
136 span.time-right(v-if="!!virtualClocks[0][1]")
137 | {{ virtualClocks[0][1] }}
140 :class="{connected: isConnected(1)}"
141 :uid="game.players[1].id"
142 :uname="game.players[1].name"
145 v-if="game.score=='*'"
146 :class="{yourturn: !!vr && vr.turn == 'b'}"
148 span.time-left {{ virtualClocks[1][0] }}
149 span.time-separator(v-if="!!virtualClocks[1][1]") :
150 span.time-right(v-if="!!virtualClocks[1][1]")
151 | {{ virtualClocks[1][1] }}
154 :class="{connected: isConnected(0)}"
155 :uid="game.players[0].id"
156 :uname="game.players[0].name"
160 :class="{connected: isConnected(1)}"
161 :uid="game.players[1].id"
162 :uname="game.players[1].name"
164 div(v-if="game.score=='*'")
165 span.time(:class="{yourturn: !!vr && vr.turn == 'w'}")
166 span.time-left {{ virtualClocks[0][0] }}
167 span.time-separator(v-if="!!virtualClocks[0][1]") :
168 span.time-right(v-if="!!virtualClocks[0][1]")
169 | {{ virtualClocks[0][1] }}
171 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
172 span.time-left {{ virtualClocks[1][0] }}
173 span.time-separator(v-if="!!virtualClocks[1][1]") :
174 span.time-right(v-if="!!virtualClocks[1][1]")
175 | {{ virtualClocks[1][1] }}
179 @newmove="processMove"
184 import BaseGame from "@/components/BaseGame.vue";
185 import UserBio from "@/components/UserBio.vue";
186 import Chat from "@/components/Chat.vue";
187 import { store } from "@/store";
188 import { GameStorage } from "@/utils/gameStorage";
189 import { ImportgameStorage } from "@/utils/importgameStorage";
190 import { ppt } from "@/utils/datetime";
191 import { notify } from "@/utils/notifications";
192 import { ajax } from "@/utils/ajax";
193 import { extractTime } from "@/utils/timeControl";
194 import { getRandString } from "@/utils/alea";
195 import { getScoreMessage } from "@/utils/scoring";
196 import { getFullNotation } from "@/utils/notation";
197 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
198 import { processModalClick } from "@/utils/modalClick";
199 import { playMove, getFilteredMove } from "@/utils/playUndo";
200 import { ArrayFun } from "@/utils/array";
201 import afterRawLoad from "@/utils/afterRawLoad";
202 import params from "@/parameters";
213 // gameRef can point to a corr game, local game or remote live game
216 game: {}, //passed to BaseGame
217 focus: !document.hidden, //will not always work... TODO
218 // virtualClocks will be initialized from true game.clocks
219 // TODO: clock update triggers re-rendering. Should be out of Vue
221 vr: null, //"variant rules" object initialized from FEN
227 people: {}, //players + observers
228 lastate: undefined, //used if opponent send lastate before game is ready
229 repeat: {}, //detect position repetition
230 curDiag: "", //for corr moves confirmation
232 roomInitialized: false,
233 // If asklastate got no reply, ask again:
235 gotMoveIdx: -1, //last move index received
236 // If newmove got no pingback, send again:
237 opponentGotMove: false,
239 socketCloseListener: 0,
240 // Incomplete info games: show move played
242 // Intervals from setInterval():
246 // Related to (killing of) self multi-connects:
251 $route: function(to, from) {
252 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
254 this.cleanBeforeDestroy();
255 else if (from.params["id"] != to.params["id"]) {
256 // Change everything:
257 this.cleanBeforeDestroy();
258 let boardDiv = document.querySelector(".game");
260 // In case of incomplete information variant:
261 boardDiv.style.visibility = "hidden";
266 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
269 // NOTE: some redundant code with Hall.vue (mostly related to people array)
270 created: function() {
273 mounted: function() {
274 document.getElementById("chatWrap")
275 .addEventListener("click", (e) => {
276 processModalClick(e, () => {
277 this.toggleChat("close")
280 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
282 document.getElementById(eltName)
283 .addEventListener("click", processModalClick);
287 beforeDestroy: function() {
288 this.cleanBeforeDestroy();
291 cleanBeforeDestroy: function() {
292 clearInterval(this.socketCloseListener);
293 document.removeEventListener('visibilitychange', this.visibilityChange);
294 window.removeEventListener('focus', this.onFocus);
295 window.removeEventListener('blur', this.onBlur);
296 if (!!this.askLastate) clearInterval(this.askLastate);
297 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
298 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
299 this.conn.removeEventListener("message", this.socketMessageListener);
300 this.send("disconnect");
303 visibilityChange: function() {
304 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
305 this.focus = (document.visibilityState == "visible");
306 this.send(this.focus ? "getfocus" : "losefocus");
308 onFocus: function() {
310 this.send("getfocus");
314 this.send("losefocus");
316 isLargeScreen: function() {
317 return window.innerWidth >= 768;
319 btnTooltipClass: function(thing) {
321 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
324 { tooltip: !("ontouchstart" in window) },
329 someAnonymousPresent: function() {
331 Object.values(this.people).some(p =>
332 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
336 requestLastate: function(sid) {
337 // TODO: maybe also find opponent SID ?
339 // this.game.players.find(p => p.sid != this.st.user.sid).sid;
340 this.send("asklastate", { target: sid });
342 this.askLastate = setInterval(
344 // Ask at most 3 times:
345 // if no reply after that there should be a network issue.
351 this.send("asklastate", { target: sid });
354 else clearInterval(this.askLastate);
359 atCreation: function() {
360 document.addEventListener('visibilitychange', this.visibilityChange);
361 window.addEventListener('focus', this.onFocus);
362 window.addEventListener('blur', this.onBlur);
363 // 0] (Re)Set variables
364 this.gameRef = this.$route.params["id"];
365 // next = next corr games IDs to navigate faster (if applicable)
366 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
367 // Always add myself to players' list
368 const my = this.st.user;
369 const tmpId = getRandString();
377 [tmpId]: { focus: true }
382 players: [{ name: "" }, { name: "" }],
386 let chatComp = this.$refs["chatcomp"];
387 if (!!chatComp) chatComp.chats = [];
388 this.virtualClocks = [[0,0], [0,0]];
390 this.rulesContent = "";
392 this.lastateAsked = false;
393 this.rematchOffer = "";
394 this.lastate = undefined;
395 this.roomInitialized = false;
396 this.gotLastate = false;
397 this.gotMoveIdx = -1;
398 this.opponentGotMove = false;
399 this.askLastate = null;
400 this.retrySendmove = null;
401 this.clockUpdate = null;
402 this.newConnect = {};
403 // 1] Initialize connection
404 this.connexionString =
406 "/?sid=" + this.st.user.sid +
407 "&id=" + this.st.user.id +
410 // Discard potential "/?next=[...]" for page indication:
411 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
412 this.conn = new WebSocket(this.connexionString);
413 this.conn.addEventListener("message", this.socketMessageListener);
414 this.socketCloseListener = setInterval(
416 if (this.conn.readyState == 3) {
417 this.conn.removeEventListener(
418 "message", this.socketMessageListener);
419 this.conn = new WebSocket(this.connexionString);
420 this.conn.addEventListener("message", this.socketMessageListener);
421 const oppSid = this.getOppsid();
422 if (!!oppSid) this.requestLastate(oppSid); //in case of
427 // Socket init required before loading remote game:
428 const socketInit = callback => {
429 if (this.conn.readyState == 1)
433 // Socket not ready yet (initial loading)
434 // NOTE: first arg is Websocket object, unused here:
435 this.conn.onopen = () => callback();
437 this.fetchGame((game) => {
440 // Patch for retro-compatibility (TODO: remove it)
441 game.options = { randomness: game.randomness };
442 delete game["randomness"];
444 else game.options = JSON.parse(game.options);
445 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
448 // Live game stored remotely: need socket to retrieve it
449 // NOTE: the callback "roomInit" will be lost, so it's not provided.
450 // --> It will be given when receiving "fullgame" socket event.
451 socketInit(() => { this.send("askfullgame"); });
454 roomInit: function() {
455 if (!this.roomInitialized) {
456 // Notify the room only now that I connected, because
457 // messages might be lost otherwise (if game loading is slow)
458 this.send("connect");
459 this.send("pollclients");
460 // We may ask fullgame several times if some moves are lost,
461 // but room should be init only once:
462 this.roomInitialized = true;
465 send: function(code, obj) {
466 if (!!this.conn && this.conn.readyState == 1)
467 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
469 isConnected: function(index) {
470 const player = this.game.players[index];
471 // Is it me ? In this case no need to bother with focus
473 this.st.user.sid == player.sid ||
474 (!!player.name && this.st.user.id == player.id)
476 // Still have to check for name (because of potential multi-accounts
477 // on same browser, although this should be rare...)
478 return (!this.st.user.name || this.st.user.name == player.name);
480 // Try to find a match in people:
484 Object.keys(this.people).some(sid => {
487 Object.values(this.people[sid].tmpIds).some(v => v.focus)
494 Object.values(this.people).some(p => {
497 Object.values(p.tmpIds).some(v => v.focus)
503 getOppsid: function() {
504 let oppsid = this.game.oppsid;
506 oppsid = Object.keys(this.people).find(
507 sid => this.people[sid].id == this.game.oppid
510 // oppsid is useful only if opponent is online:
511 if (!!oppsid && !!this.people[oppsid]) return oppsid;
514 // NOTE: action if provided is always a closing action
515 toggleChat: function(action) {
516 if (!action && document.getElementById("modalChat").checked)
518 document.getElementById("inputChat").focus();
520 document.getElementById("chatBtn").classList.remove("somethingnew");
521 if (!!this.game.mycolor) {
522 // Update "chatRead" variable either on server or locally
523 if (this.game.type == "corr")
524 this.updateCorrGame({ chatRead: this.game.mycolor });
525 else if (this.game.type == "live")
526 GameStorage.update(this.gameRef, { chatRead: true });
530 processChat: function(chat) {
531 this.send("newchat", { data: chat });
532 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
533 if (!!this.game.mycolor) {
534 if (this.game.type == "corr")
535 this.updateCorrGame({ chat: chat });
538 chat.added = Date.now();
539 GameStorage.update(this.gameRef, { chat: chat });
543 clearChat: function() {
544 if (!!this.game.mycolor) {
545 if (this.game.type == "corr") {
549 { data: { gid: this.game.id } }
554 GameStorage.update(this.gameRef, { delchat: true });
556 this.$set(this.game, "chats", []);
559 getGameType: function(game) {
560 if (!!game.id.toString().match(/^i/)) return "import";
561 return (game.cadence.indexOf("d") >= 0 ? "corr" : "live");
563 // Notify something after a new move (to opponent and me on MyGames page)
564 notifyMyGames: function(thing, data) {
569 targets: this.game.players.map(p => {
570 return { sid: p.sid, id: p.id };
575 showNextGame: function() {
576 // Did I play in current game? If not, add it to nextIds list
577 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
578 this.nextIds.unshift(this.game.id);
579 const nextGid = this.nextIds.pop();
581 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
583 socketMessageListener: function(msg) {
584 if (!this.conn) return;
585 const data = JSON.parse(msg.data);
588 // TODO: shuffling and random filtering on server,
589 // if the room is really crowded.
590 Object.keys(data.sockIds).forEach(sid => {
591 if (sid != this.st.user.sid) {
592 this.send("askidentity", { target: sid });
593 this.people[sid] = { tmpIds: data.sockIds[sid] };
596 // Complete my tmpIds:
597 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
602 if (!this.people[data.from[0]]) {
603 // focus depends on the tmpId (e.g. tab)
609 [data.from[1]]: { focus: true }
613 // For self multi-connects tests:
614 this.newConnect[data.from[0]] = true;
615 this.send("askidentity", { target: data.from[0] });
618 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
619 this.$forceUpdate(); //TODO: shouldn't be required
623 if (!this.people[data.from[0]]) return;
624 delete this.people[data.from[0]].tmpIds[data.from[1]];
625 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
626 this.$delete(this.people, data.from[0]);
627 else this.$forceUpdate(); //TODO: shouldn't be required
630 let player = this.people[data.from[0]];
632 player.tmpIds[data.from[1]].focus = true;
633 this.$forceUpdate(); //TODO: shouldn't be required
638 let player = this.people[data.from[0]];
640 player.tmpIds[data.from[1]].focus = false;
641 this.$forceUpdate(); //TODO: shouldn't be required
645 case "askidentity": {
646 // Request for identification
648 // Decompose to avoid revealing email
649 name: this.st.user.name,
650 sid: this.st.user.sid,
653 this.send("identity", { data: me, target: data.from });
657 const user = data.data;
658 let player = this.people[user.sid];
659 // player.tmpIds is already set
660 player.name = user.name;
662 if (this.game.type == "live") {
664 this.game.players.findIndex(p => p.sid == this.st.user.sid);
665 // Sometimes a player name isn't stored yet (TODO: why?)
668 !this.game.players[1 - myGidx].name &&
669 this.game.players[1 - myGidx].sid == user.sid &&
672 this.game.players[1-myGidx].name = user.name;
675 { playerName: { idx: 1 - myGidx, name: user.name } }
679 this.$forceUpdate(); //TODO: shouldn't be required
680 // If I multi-connect, kill current connexion if no mark (I'm older)
681 if (this.newConnect[user.sid]) {
682 delete this.newConnect[user.sid];
685 user.id == this.st.user.id &&
686 user.sid != this.st.user.sid
688 this.cleanBeforeDestroy();
689 alert(this.st.tr["New connexion detected: tab now offline"]);
693 // Ask potentially missed last state, if opponent and I play
696 !!this.game.mycolor &&
697 this.game.type == "live" &&
698 this.game.players.some(p => p.sid == user.sid)
700 this.requestLastate(user.sid);
705 // Send current (live or import) game,
706 // if not asked by any of the players
708 this.game.type != "corr" &&
709 this.game.players.every(p => p.sid != data.from[0])
713 // FEN is current position, unused for now
715 players: this.game.players,
717 cadence: this.game.cadence,
718 score: this.game.score
720 this.send("game", { data: myGame, target: data.from });
724 const gameToSend = Object.keys(this.game)
727 "id","fen","players","vid","cadence","fenStart","options",
728 "moves","clocks","score","drawOffer","rematchOffer"
732 obj[k] = this.game[k];
737 this.send("fullgame", { data: gameToSend, target: data.from });
740 if (!!data.data.empty) {
741 alert(this.st.tr["The game should be in another tab"]);
745 // Callback "roomInit" to poll clients only after game is loaded
746 this.loadVariantThenGame(data.data, this.roomInit);
749 // Sending informative last state if I played a move or score != "*"
750 // If the game or moves aren't loaded yet, delay the sending:
751 // TODO: socket init after game load, so the game is supposedly ready
752 if (!this.game || !this.game.moves) this.lastateAsked = true;
753 else this.sendLastate(data.from);
755 // TODO: possible bad scenario: reload page while oppponent sends a
756 // move => get both lastate and newmove, process both, add move twice.
757 // Confirm scenario? Fix?
759 // Got opponent infos about last move
760 this.gotLastate = true;
761 this.lastate = data.data;
762 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
763 this.gotMoveIdx = this.lastate.movesCount - 1;
764 if (this.game.rendered)
765 // Game is rendered (Board component)
766 this.processLastate();
767 // Else: will be processed when game is ready
773 //console.log("Receive move");
774 //console.log(data.data);
775 //moveslist not updated when receiving a move? (see in BaseGame)
777 const movePlus = data.data;
778 const movesCount = this.game.moves.length;
780 movePlus.index < movesCount ||
781 this.gotMoveIdx >= movePlus.index
783 // Opponent re-send but we already have the move:
784 // (maybe he didn't receive our pingback...)
785 this.send("gotmove", {data: movePlus.index, target: data.from});
788 this.gotMoveIdx = movePlus.index;
789 const receiveMyMove = (movePlus.color == this.game.mycolor);
790 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
791 if (!receiveMyMove && !!this.game.mycolor) {
792 // Notify opponent that I got the move:
795 { data: movePlus.index, target: data.from }
797 // And myself if I'm elsewhere:
803 (this.game.players[moveColIdx].name || "@nonymous") +
809 if (movePlus.cancelDrawOffer) {
810 // Opponent refuses draw
812 // NOTE for corr games: drawOffer reset by player in turn
814 this.game.type == "live" &&
815 !!this.game.mycolor &&
818 GameStorage.update(this.gameRef, { drawOffer: "" });
821 this.$refs["basegame"].play(movePlus.move, "received");
822 // Freeze time while the move is being play
823 // (TODO: a callback would be cleaner here)
824 clearInterval(this.clockUpdate);
825 this.clockUpdate = null;
826 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
827 // 250 = length of animation, 500 = delay between sub-moves
829 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
830 // Incomplete information: no move animation
834 this.game.clocks[moveColIdx] = movePlus.clock;
837 { receiveMyMove: receiveMyMove }
846 this.opponentGotMove = true;
847 // Now his clock starts running on my side:
848 const oppIdx = ['w','b'].indexOf(this.vr.turn);
849 // NOTE: next line to avoid multi-resetClocks when several tabs
850 // on same game, resulting in a faster countdown.
851 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
856 const score = (data.data == "b" ? "1-0" : "0-1");
857 const side = (data.data == "w" ? "White" : "Black");
858 this.gameOver(score, side + " surrender");
861 this.gameOver("?", "Stop");
864 this.gameOver("1/2", data.data);
867 // NOTE: observers don't know who offered draw
868 this.drawOffer = "received";
869 if (!!this.game.mycolor && this.game.type == "live") {
872 { drawOffer: V.GetOppCol(this.game.mycolor) }
877 // NOTE: observers don't know who offered rematch
878 this.rematchOffer = data.data ? "received" : "";
879 if (!!this.game.mycolor && this.game.type == "live") {
882 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
887 // A game started, redirect if I'm playing in
888 const gameInfo = data.data;
889 const gameType = this.getGameType(gameInfo);
891 gameType == "live" &&
892 gameInfo.players.some(p => p.sid == this.st.user.sid)
894 this.addAndGotoLiveGame(gameInfo);
897 gameType == "corr" &&
898 this.st.user.id > 0 &&
899 gameInfo.players.some(p => p.id == this.st.user.id)
901 this.$router.push("/game/" + gameInfo.id);
904 this.rematchId = gameInfo.id;
905 document.getElementById("modalRules").checked = false;
906 document.getElementById("modalScore").checked = false;
907 document.getElementById("modalRematch").checked = true;
912 let chat = data.data;
913 this.$refs["chatcomp"].newChat(chat);
914 if (this.game.type == "live") {
915 chat.added = Date.now();
916 if (!!this.game.mycolor)
917 GameStorage.update(this.gameRef, { chat: chat });
919 if (!document.getElementById("modalChat").checked)
920 document.getElementById("chatBtn").classList.add("somethingnew");
925 updateCorrGame: function(obj, callback) {
935 if (!!callback) callback();
940 sendLastate: function(target) {
941 // Send our "last state" informations to opponent
942 const L = this.game.moves.length;
943 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
946 (L > 0 && this.vr.turn != this.game.mycolor)
947 ? this.game.moves[L - 1]
949 clock: this.game.clocks[myIdx],
950 // Since we played a move (or abort or resign),
951 // only drawOffer=="sent" is possible
952 drawSent: this.drawOffer == "sent" ? true : undefined,
953 rematchSent: this.rematchOffer == "sent" ? true : undefined,
954 score: this.game.score != "*" ? this.game.score : undefined,
955 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
958 this.send("lastate", { data: myLastate, target: target });
960 // lastate was received, but maybe game wasn't ready yet:
961 processLastate: function() {
962 const data = this.lastate;
963 this.lastate = undefined; //security...
965 const oppCol = V.GetOppCol(this.game.mycolor);
966 if (!!data.rematchSent) {
967 if (this.game.rematchOffer != oppCol) {
968 // Opponent sended rematch offer while we were offline:
969 this.rematchOffer = "received";
972 { rematchOffer: oppCol }
977 if (this.game.rematchOffer == oppCol) {
978 // Opponent cancelled rematch offer while we were offline:
979 this.rematchOffer = "";
988 const L = this.game.moves.length;
989 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
990 this.game.clocks[oppIdx] = data.clock;
991 if (data.movesCount > L) {
992 // Just got last move from him
993 this.$refs["basegame"].play(data.lastMove, "received");
994 this.processMove(data.lastMove);
997 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
1000 if (!!data.drawSent) this.drawOffer = "received";
1002 this.drawOffer = "";
1003 if (this.game.score == "*")
1004 this.gameOver(data.score, data.scoreMsg);
1008 clickDraw: function() {
1009 if (!this.game.mycolor || this.game.type == "import") return;
1010 if (["received", "threerep"].includes(this.drawOffer)) {
1011 if (!confirm(this.st.tr["Accept draw?"])) return;
1013 this.drawOffer == "received"
1014 ? "Mutual agreement"
1015 : "Three repetitions";
1016 this.send("draw", { data: message });
1017 this.gameOver("1/2", message);
1019 else if (this.drawOffer == "") {
1020 // No effect if drawOffer == "sent"
1021 if (this.game.mycolor != this.vr.turn) {
1022 alert(this.st.tr["Draw offer only in your turn"]);
1025 if (!confirm(this.st.tr["Offer draw?"])) return;
1026 this.drawOffer = "sent";
1027 this.send("drawoffer");
1028 if (this.game.type == "live") {
1031 { drawOffer: this.game.mycolor }
1034 else this.updateCorrGame({ drawOffer: this.game.mycolor });
1037 addAndGotoLiveGame: function(gameInfo, callback) {
1038 const game = Object.assign(
1042 // (other) Game infos: constant
1043 fenStart: gameInfo.fen,
1044 created: Date.now(),
1045 // Game state (including FEN): will be updated
1047 clocks: [-1, -1], //-1 = unstarted
1052 GameStorage.add(game, (err) => {
1053 // No error expected.
1055 if (this.st.settings.sound)
1056 new Audio("/sounds/newgame.flac").play().catch(() => {});
1057 if (!!callback) callback();
1058 this.$router.push("/game/" + gameInfo.id);
1062 clickRematch: function() {
1063 if (!this.game.mycolor || this.game.type == "import") return;
1064 if (this.rematchOffer == "received") {
1065 // Start a new game!
1067 id: getRandString(), //ignored if corr
1068 fen: V.GenRandInitFen(this.game.options),
1069 options: JSON.stringify(this.game.options),
1070 players: [this.game.players[1], this.game.players[0]],
1072 cadence: this.game.cadence
1074 const notifyNewGame = () => {
1075 this.send("rnewgame", { data: gameInfo });
1076 // To main Hall if corr game:
1077 if (this.game.type == "corr")
1078 this.send("newgame", { data: gameInfo, page: "/" });
1079 // Also to MyGames page:
1080 this.notifyMyGames("newgame", gameInfo);
1082 if (this.game.type == "live") {
1085 { rematchOffer: "" }
1087 // Increment game stats counter in DB
1091 { data: { vid: gameInfo.vid } }
1093 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1097 this.updateCorrGame({ rematchOffer: 'n' });
1102 data: { gameInfo: gameInfo },
1103 success: (response) => {
1104 gameInfo.id = response.id;
1106 this.$router.push("/game/" + response.id);
1112 else if (this.rematchOffer == "") {
1113 this.rematchOffer = "sent";
1114 this.send("rematchoffer", { data: true });
1115 if (this.game.type == "live") {
1118 { rematchOffer: this.game.mycolor }
1121 else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1123 else if (this.rematchOffer == "sent") {
1124 // Toggle rematch offer (on --> off)
1125 this.rematchOffer = "";
1126 this.send("rematchoffer", { data: false });
1127 if (this.game.type == "live") {
1130 { rematchOffer: '' }
1133 else this.updateCorrGame({ rematchOffer: 'n' });
1136 abortGame: function() {
1137 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1139 this.gameOver("?", "Stop");
1142 resign: function() {
1143 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1145 this.send("resign", { data: this.game.mycolor });
1146 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1147 const side = (this.game.mycolor == "w" ? "White" : "Black");
1148 this.gameOver(score, side + " surrender");
1150 loadGame: function(game, callback) {
1151 const gtype = game.type || this.getGameType(game);
1152 const tc = extractTime(game.cadence);
1153 const myIdx = game.players.findIndex(p => {
1155 p.sid == this.st.user.sid ||
1156 (!!p.name && p.id == this.st.user.id)
1159 // Sometimes the name isn't stored yet (TODO: why?)
1163 !game.players[myIdx].name &&
1166 game.players[myIdx].name = this.st.user.name;
1169 { playerName: { idx: myIdx, name: this.st.user.name } }
1172 // "mycolor" is undefined for observers
1173 const mycolor = [undefined, "w", "b"][myIdx + 1];
1174 if (gtype == "corr") {
1175 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1176 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1177 // NOTE: clocks in seconds
1178 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1179 game.clocks = [tc.mainTime, tc.mainTime];
1180 const L = game.moves.length;
1181 if (game.score == "*") {
1184 game.clocks[L % 2] -=
1185 (Date.now() - game.moves[L-1].played) / 1000;
1188 // Now that we used idx and played, re-format moves as for live games
1189 game.moves = game.moves.map(m => m.squares);
1191 else if (gtype == "live") {
1192 if (game.clocks[0] < 0) {
1193 // Game is unstarted. clock is ignored until move 2
1194 game.clocks = [tc.mainTime, tc.mainTime];
1196 // I play in this live game
1199 { clocks: game.clocks }
1203 else if (!!game.initime)
1204 // It's my turn: clocks not updated yet
1205 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1208 // gtype == "import"
1209 game.clocks = [tc.mainTime, tc.mainTime];
1210 // Live games before 26/03/2020 don't have chat history:
1211 if (!game.chats) game.chats = []; //TODO: remove line
1212 // Sort chat messages from newest to oldest
1213 game.chats.sort((c1, c2) => c2.added - c1.added);
1216 game.chats.length > 0 &&
1217 (!game.chatRead || game.chatRead < game.chats[0].added)
1219 // A chat message arrived since my last reading:
1220 document.getElementById("chatBtn").classList.add("somethingnew");
1222 // TODO: merge next 2 "if" conditions
1223 if (!!game.drawOffer) {
1224 if (game.drawOffer == "t")
1225 // Three repetitions
1226 this.drawOffer = "threerep";
1228 // Draw offered by any of the players:
1229 if (myIdx < 0) this.drawOffer = "received";
1231 // I play in this game:
1233 (game.drawOffer == "w" && myIdx == 0) ||
1234 (game.drawOffer == "b" && myIdx == 1)
1236 this.drawOffer = "sent";
1237 else this.drawOffer = "received";
1241 if (!!game.rematchOffer) {
1242 if (myIdx < 0) this.rematchOffer = "received";
1244 // I play in this game:
1246 (game.rematchOffer == "w" && myIdx == 0) ||
1247 (game.rematchOffer == "b" && myIdx == 1)
1249 this.rematchOffer = "sent";
1251 else this.rematchOffer = "received";
1254 this.repeat = {}; //reset: scan past moves' FEN:
1256 this.vr = new V(game.fenStart);
1258 game.moves.forEach(m => {
1259 playMove(m, this.vr);
1260 const fenIdx = this.vr.getFenForRepeat();
1261 this.repeat[fenIdx] = this.repeat[fenIdx]
1262 ? this.repeat[fenIdx] + 1
1265 // Imported games don't have current FEN
1266 if (!game.fen) game.fen = this.vr.getFen();
1267 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1268 this.game = Object.assign(
1269 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1272 increment: tc.increment,
1274 // opponent sid not strictly required (or available), but easier
1275 // at least oppsid or oppid is available anyway:
1276 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1277 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1281 this.$refs["basegame"].re_setVariables(this.game);
1283 this.gotMoveIdx = game.moves.length - 1;
1284 // If we arrive here after 'nextGame' action, the board might be hidden
1285 let boardDiv = document.querySelector(".game");
1286 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1287 boardDiv.style.visibility = "visible";
1288 this.re_setClocks();
1289 this.$nextTick(() => {
1290 this.game.rendered = true;
1291 // Did lastate arrive before game was rendered?
1292 if (!!this.lastate) this.processLastate();
1294 if (this.lastateAsked) {
1295 this.lastateAsked = false;
1296 this.sendLastate(game.oppsid);
1298 if (!!callback) callback();
1300 loadVariantThenGame: async function(game, callback) {
1301 const afterSetVname = async () => {
1302 await import("@/variants/" + game.vname + ".js")
1303 .then((vModule) => {
1304 window.V = vModule[game.vname + "Rules"];
1305 this.loadGame(game, callback);
1310 "raw-loader!@/translations/rules/" +
1311 game.vname + "/" + this.st.lang + ".pug"
1313 ).replace(/(fen:)([^:]*):/g, replaceByDiag);
1315 let variant = undefined;
1316 const trySetVname = setInterval(
1318 // this.st.variants might be uninitialized (variant == null)
1319 variant = this.st.variants.find(v => {
1320 return v.id == game.vid || v.name == game.vname
1323 clearInterval(trySetVname);
1324 game.vname = variant.name;
1325 game.vdisp = variant.display;
1331 // 3 cases for loading a game:
1332 // - from indexedDB (running or completed live game I play)
1333 // - from server (one correspondance game I play[ed] or not)
1334 // - from remote peer (one live game I don't play, finished or not)
1335 fetchGame: function(callback) {
1337 Number.isInteger(this.gameRef) ||
1338 !isNaN(parseInt(this.gameRef, 10))
1340 // corr games identifiers are integers
1345 data: { gid: this.gameRef },
1347 res.game.moves.forEach(m => {
1348 m.squares = JSON.parse(m.squares);
1355 else if (!!this.gameRef.match(/^i/))
1356 // Game import (maybe remote)
1357 ImportgameStorage.get(this.gameRef, callback);
1359 // Local live game (or remote)
1360 GameStorage.get(this.gameRef, callback);
1362 re_setClocks: function() {
1363 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1364 if (this.game.moves.length < 2 || this.game.score != "*") {
1365 // 1st move not completed yet, or game over: freeze time
1368 const currentTurn = this.vr.turn;
1369 const currentMovesCount = this.game.moves.length;
1370 const colorIdx = ["w", "b"].indexOf(currentTurn);
1371 this.clockUpdate = setInterval(
1374 this.game.clocks[colorIdx] < 0 ||
1375 this.game.moves.length > currentMovesCount ||
1376 this.game.score != "*"
1378 clearInterval(this.clockUpdate);
1379 this.clockUpdate = null;
1380 if (this.game.clocks[colorIdx] < 0)
1382 currentTurn == "w" ? "0-1" : "1-0",
1390 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1397 // Update variables and storage after a move:
1398 processMove: function(move, data) {
1399 if (this.game.type == "import")
1400 // Shouldn't receive any messages in this mode:
1402 if (!data) data = {};
1403 const moveCol = this.vr.turn;
1404 const colorIdx = ["w", "b"].indexOf(moveCol);
1405 const nextIdx = 1 - colorIdx;
1406 const doProcessMove = () => {
1407 const origMovescount = this.game.moves.length;
1408 // The move is (about to be) played: stop clock
1409 clearInterval(this.clockUpdate);
1410 this.clockUpdate = null;
1411 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1412 if (this.drawOffer == "received")
1414 this.drawOffer = "";
1415 if (this.game.type == "live" && origMovescount >= 2) {
1416 this.game.clocks[colorIdx] += this.game.increment;
1417 // For a correct display in casqe of disconnected opponent:
1421 ppt(this.game.clocks[colorIdx]).split(':')
1423 GameStorage.update(this.gameRef, {
1424 // It's not my turn anymore:
1429 // Update current game object:
1430 playMove(move, this.vr);
1432 // Received move, score is computed in BaseGame, but maybe not yet.
1433 // ==> Compute it here, although this is redundant (TODO)
1434 data.score = this.vr.getCurrentScore();
1435 if (data.score != "*") this.gameOver(data.score);
1436 this.game.moves.push(move);
1437 this.game.fen = this.vr.getFen();
1438 if (this.game.type == "corr") {
1439 // In corr games, just reset clock to mainTime:
1440 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1442 if (!V.IgnoreRepetition) {
1443 // If repetition detected, consider that a draw offer was received:
1444 const fenObj = this.vr.getFenForRepeat();
1445 this.repeat[fenObj] =
1446 !!this.repeat[fenObj]
1447 ? this.repeat[fenObj] + 1
1449 if (this.repeat[fenObj] >= 3) {
1450 if (this.vr.loseOnRepetition())
1451 this.gameOver(moveCol == "w" ? "0-1" : "1-0", "Repetition");
1452 else this.drawOffer = "threerep";
1454 else if (this.drawOffer == "threerep") this.drawOffer = "";
1456 if (!!this.game.mycolor && !data.receiveMyMove) {
1457 // NOTE: 'var' to see that variable outside this block
1458 var filtered_move = getFilteredMove(move);
1460 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1461 // Notify turn on MyGames page:
1470 // Since corr games are stored at only one location, update should be
1471 // done only by one player for each move:
1473 this.game.type == "live" &&
1474 !!this.game.mycolor &&
1475 moveCol != this.game.mycolor &&
1476 this.game.moves.length >= 2
1478 // Receive a move: update initime
1479 this.game.initime = Date.now();
1480 GameStorage.update(this.gameRef, {
1481 // It's my turn now!
1482 initime: this.game.initime
1486 !!this.game.mycolor &&
1487 !data.receiveMyMove &&
1488 (this.game.type == "live" || moveCol == this.game.mycolor)
1491 switch (this.drawOffer) {
1496 drawCode = this.game.mycolor;
1499 drawCode = V.GetOppCol(this.game.mycolor);
1502 if (this.game.type == "corr") {
1503 // corr: only move, fen and score
1504 this.updateCorrGame({
1507 squares: filtered_move,
1510 // Code "n" for "None" to force reset (otherwise it's ignored)
1511 drawOffer: drawCode || "n"
1515 const updateStorage = () => {
1516 GameStorage.update(this.gameRef, {
1518 move: filtered_move,
1519 moveIdx: origMovescount,
1520 clocks: this.game.clocks,
1524 // The active tab can update storage immediately
1525 if (this.focus) updateStorage();
1526 // Small random delay otherwise
1527 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1530 // Send move ("newmove" event) to people in the room (if our turn)
1531 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1533 move: filtered_move,
1534 index: origMovescount,
1535 // color is required to check if this is my move
1536 // (if several tabs opened)
1538 cancelDrawOffer: this.drawOffer == ""
1540 if (this.game.type == "live")
1541 sendMove["clock"] = this.game.clocks[colorIdx];
1542 // (Live) Clocks will re-start when the opponent pingback arrive
1543 this.opponentGotMove = false;
1544 this.send("newmove", {data: sendMove});
1545 // If the opponent doesn't reply gotmove soon enough, re-send move:
1546 // Do this at most 2 times, because more would mean network issues,
1547 // opponent would then be expected to disconnect/reconnect.
1549 const currentUrl = document.location.href;
1550 this.retrySendmove = setInterval(
1554 this.opponentGotMove ||
1555 document.location.href != currentUrl //page change
1557 clearInterval(this.retrySendmove);
1560 const oppsid = this.getOppsid();
1562 // Opponent is disconnected: he'll ask last state
1563 clearInterval(this.retrySendmove);
1565 this.send("newmove", { data: sendMove, target: oppsid });
1573 // Not my move or I'm an observer: just start other player's clock
1574 this.re_setClocks();
1577 this.game.type == "corr" &&
1578 moveCol == this.game.mycolor &&
1581 let boardDiv = document.querySelector(".game");
1582 const afterSetScore = () => {
1584 if (this.st.settings.gotonext && this.nextIds.length > 0)
1585 this.showNextGame();
1587 // The board might have been hidden:
1588 if (boardDiv.style.visibility == "hidden")
1589 boardDiv.style.visibility = "visible";
1590 if (data.score == "*") this.re_setClocks();
1593 if (!V.CorrConfirm) {
1597 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1598 // We may play several moves in a row: in case of, remove listener:
1599 let elClone = el.cloneNode(true);
1600 el.parentNode.replaceChild(elClone, el);
1601 elClone.addEventListener(
1604 document.getElementById("modalConfirm").checked = false;
1605 if (!!data.score && data.score != "*")
1607 this.gameOver(data.score, null, afterSetScore);
1608 else afterSetScore();
1611 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1612 const arMove = (Array.isArray(move) ? move : [move]);
1613 for (let i = 0; i < arMove.length; i++)
1614 V.PlayOnBoard(this.vr.board, arMove[i]);
1615 const position = this.vr.getBaseFen();
1616 for (let i = arMove.length - 1; i >= 0; i--)
1617 V.UndoOnBoard(this.vr.board, arMove[i]);
1618 if (["all","byrow"].includes(V.ShowMoves)) {
1619 this.curDiag = getDiagram({
1621 orientation: V.CanFlip ? this.game.mycolor : "w",
1622 color: this.game.mycolor,
1625 document.querySelector("#confirmDiv > .card").style.width =
1626 boardDiv.offsetWidth + "px";
1629 // Incomplete information: just ask confirmation
1630 // Hide the board, because otherwise it could reveal infos
1631 boardDiv.style.visibility = "hidden";
1632 this.moveNotation = getFullNotation(move);
1634 document.getElementById("modalConfirm").checked = true;
1638 if (!!data.score && data.score != "*")
1639 this.gameOver(data.score, null, doProcessMove);
1640 else doProcessMove();
1643 cancelMove: function() {
1644 let boardDiv = document.querySelector(".game");
1645 if (boardDiv.style.visibility == "hidden")
1646 boardDiv.style.visibility = "visible";
1647 document.getElementById("modalConfirm").checked = false;
1648 this.$refs["basegame"].cancelLastMove();
1650 // In corr games, callback to change page only after score is set:
1651 gameOver: function(score, scoreMsg, callback) {
1652 this.game.score = score;
1653 if (!scoreMsg) scoreMsg = getScoreMessage(score, V.ReverseColors);
1654 this.game.scoreMsg = scoreMsg;
1655 document.getElementById("modalRules").checked = false;
1656 // Display result in a un-missable way:
1657 document.getElementById("modalScore").checked = true;
1658 this.$set(this.game, "scoreMsg", scoreMsg);
1659 const myIdx = this.game.players.findIndex(p => {
1661 p.sid == this.st.user.sid ||
1662 (!!p.name && p.id == this.st.user.id)
1666 // OK, I play in this game
1671 if (this.game.type == "live") {
1672 GameStorage.update(this.gameRef, scoreObj);
1673 // Notify myself locally if I'm elsewhere:
1677 { body: score + " : " + scoreMsg }
1680 if (!!callback) callback();
1682 else this.updateCorrGame(scoreObj, callback);
1683 // Notify the score to main Hall.
1684 // TODO: only one player (currently double send)
1685 this.send("result", { gid: this.game.id, score: score });
1686 // Also to MyGames page (TODO: doubled as well...)
1695 else if (!!callback) callback();
1701 <style lang="sass" scoped>
1702 #scoreDiv > .card, #rematchDiv > .card
1710 @media screen and (max-width: 1500px)
1712 @media screen and (max-width: 1024px)
1714 @media screen and (max-width: 767px)
1724 background-color: lightgreen
1736 @media screen and (max-width: 767px)
1741 display: inline-block
1745 display: inline-block
1747 display: inline-flex
1751 @media screen and (max-width: 767px)
1760 @media screen and (max-width: 767px)
1772 background-color: #edda99
1774 display: inline-block
1778 display: inline-block
1785 @media screen and (max-width: 767px)
1787 display: inline-block
1800 animation: blink-animation 2s steps(3, start) infinite
1801 @keyframes blink-animation
1806 display: inline-block
1818 .draw-sent, .draw-sent:hover
1819 background-color: lightyellow
1821 .draw-received, .draw-received:hover
1822 background-color: #73C6B6
1824 .draw-threerep, .draw-threerep:hover
1825 background-color: #D2B4DE
1827 .rematch-sent, .rematch-sent:hover
1828 background-color: lightyellow
1830 .rematch-received, .rematch-received:hover
1831 background-color: #48C9B0
1834 background-color: #D2B4DE
1847 background-color: lightgreen
1849 background-color: red
1852 color: var(--card-fore-color)
1855 font-size: calc(1rem * var(--heading-ratio))
1857 margin: calc(1.5 * var(--universal-margin))
1861 @import "@/styles/_rules.sass"
1862 @import "@/styles/_board_squares_img.sass"