3 input#modalInfo.modal(type="checkbox")
6 data-checkbox="modalInfo"
9 label.modal-close(for="modalInfo")
10 p(v-html="infoMessage")
11 input#modalAccept.modal(type="checkbox")
12 div#acceptDiv(role="dialog")
15 span.variantName {{ curChallToAccept.vname }}
16 span {{ curChallToAccept.cadence }}
17 span {{ st.tr["with"] + " " + curChallToAccept.from.name }}
19 v-if="!!curChallToAccept.fen"
22 .button-group#buttonsTchall(:style="tchallButtonsMargin()")
23 button.acceptBtn(@click="decisionChallenge(true)")
24 span {{ st.tr["Accept challenge?"] }}
25 button.refuseBtn(@click="decisionChallenge(false)")
26 span {{ st.tr["Refuse"] }}
27 input#modalNewgame.modal(
29 @change="cadenceFocusIfOpened($event)"
33 data-checkbox="modalNewgame"
36 label#closeNewgame.modal-close(for="modalNewgame")
37 div(@keyup.enter="issueNewChallenge()")
39 label(for="selectVariant") {{ st.tr["Variant"] }} *
41 @change="loadNewchallVariant(trySetNewchallDiag)"
42 v-model="newchallenge.vid"
45 v-for="v in st.variants"
47 :selected="newchallenge.vid==v.id"
51 label(for="cadence") {{ st.tr["Cadence"] }} *
52 div#predefinedCadences
53 button(type="button") 15+5
54 button(type="button") 45+30
55 button(type="button") 3d
56 button(type="button") 7d
59 v-model="newchallenge.cadence"
60 placeholder="5+0, 1h+30s, 5d ..."
63 label(for="selectRandomLevel") {{ st.tr["Randomness"] }} *
64 select#selectRandomLevel(v-model="newchallenge.randomness")
65 option(value="0") {{ st.tr["Deterministic"] }}
66 option(value="1") {{ st.tr["Symmetric random"] }}
67 option(value="2") {{ st.tr["Asymmetric random"] }}
69 label(for="memorizeChall") {{ st.tr["Memorize"] }}
72 v-model="newchallenge.memorize"
74 fieldset(v-if="st.user.id > 0")
75 label(for="selectPlayers") {{ st.tr["Play with"] }}
76 select#selectPlayersInList(
77 v-model="newchallenge.to"
78 @change="changeChallTarget()"
82 v-for="p in Object.values(people)"
89 v-model="newchallenge.to"
91 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
94 @input="trySetNewchallDiag()"
96 v-model="newchallenge.fen"
98 .diagram(v-html="newchallenge.diag")
99 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
100 input#modalPeople.modal(
102 @click="resetSocialColor()"
106 data-checkbox="modalPeople"
109 label.modal-close(for="modalPeople")
113 v-for="sid in Object.keys(people)"
114 v-if="!!people[sid].name"
116 span {{ people[sid].name }}
117 button.player-action(
119 @click="watchGame(sid)"
121 | {{ st.tr["Observe"] }}
122 button.player-action(
123 v-else-if="isFocusedOnHall(sid)"
124 @click="challenge(sid)"
126 | {{ st.tr["Challenge"] }}
127 p.anonymous @nonymous ({{ anonymousCount() }})
131 @mychat="processChat"
136 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
138 button#peopleBtn(@click="openModalPeople()")
139 | {{ st.tr["Who's there?"] }}
140 button(@click="showNewchallengeForm()")
141 | {{ st.tr["New game"] }}
142 .row(v-if="presetChalls.length > 0")
143 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
144 h4.text-center {{ st.tr["Preset challenges"] }}
148 th {{ st.tr["Variant"] }}
149 th {{ st.tr["Cadence"] }}
150 th {{ st.tr["Random?"] }}
154 v-for="pc in presetChalls"
155 @click="newChallFromPreset(pc)"
159 td(:class="getRandomnessClass(pc)")
160 td.remove-preset(@click="removePresetChall($event, pc)")
161 img(src="/images/icons/delete.svg")
163 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
166 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
167 | {{ st.tr["Live challenges"] }}
168 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
169 | {{ st.tr["Correspondance challenges"] }}
171 v-show="cdisplay=='live'"
172 :challenges="filterChallenges('live')"
173 @click-challenge="clickChallenge"
176 v-show="cdisplay=='corr'"
177 :challenges="filterChallenges('corr')"
178 @click-challenge="clickChallenge"
182 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
183 | {{ st.tr["Live games"] }}
184 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
185 | {{ st.tr["Correspondance games"] }}
187 v-show="gdisplay=='live'"
188 :games="filterGames('live')"
190 @show-game="showGame"
192 div(v-show="gdisplay=='corr'")
194 :games="filterGames('corr')"
196 @show-game="showGame"
200 @click="loadMoreCorr()"
202 | {{ st.tr["Load more"] }}
206 import { store } from "@/store";
207 import { checkChallenge } from "@/data/challengeCheck";
208 import { notify } from "@/utils/notifications";
209 import { ArrayFun } from "@/utils/array";
210 import { ajax } from "@/utils/ajax";
211 import params from "@/parameters";
212 import { getRandString, shuffle, randInt } from "@/utils/alea";
213 import { getDiagram } from "@/utils/printDiagram";
214 import Chat from "@/components/Chat.vue";
215 import GameList from "@/components/GameList.vue";
216 import ChallengeList from "@/components/ChallengeList.vue";
217 import { GameStorage } from "@/utils/gameStorage";
218 import { processModalClick } from "@/utils/modalClick";
229 cdisplay: "live", //or corr
231 // timestamp of last showed (oldest) corr game:
232 cursor: Number.MAX_SAFE_INTEGER,
233 // hasMore == TRUE: a priori there could be more games to load
241 vid: parseInt(localStorage.getItem("vid")) || 0,
242 to: "", //name of challenged player (if any)
243 cadence: localStorage.getItem("cadence") || "",
244 randomness: parseInt(localStorage.getItem("challRandomness")) || 2,
245 // VariantRules object, stored to not interfere with
246 // diagrams of targetted challenges:
249 diag: "", //visualizing FEN
250 memorize: false //put settings in localStorage
254 curChallToAccept: {from: {}},
255 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
258 socketCloseListener: 0,
259 // Related to (killing of) self multi-connects:
264 // st.variants changes only once, at loading from [] to [...]
265 "st.variants": function() {
266 // Set potential challenges and games variant names:
267 this.challenges.concat(this.games).forEach(o => {
268 if (!o.vname) o.vname = this.getVname(o.vid);
270 if (!this.newchallenge.V && this.newchallenge.vid > 0)
271 this.loadNewchallVariant();
273 $route: function(to, from) {
274 if (to.path != "/") this.cleanBeforeDestroy();
277 created: function() {
278 document.addEventListener('visibilitychange', this.visibilityChange);
279 window.addEventListener('focus', this.onFocus);
280 window.addEventListener('blur', this.onBlur);
281 window.addEventListener("beforeunload", this.cleanBeforeDestroy);
282 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
283 this.loadNewchallVariant();
284 const my = this.st.user;
285 const tmpId = getRandString();
293 tmpId: { page: "/", focus: true }
297 const connectAndPoll = () => {
298 this.send("connect");
299 this.send("pollclientsandgamers");
301 // Initialize connection
302 this.connexionString =
304 "/?sid=" + this.st.user.sid +
305 "&id=" + this.st.user.id +
308 // Hall: path is "/" (TODO: could be hard-coded as well)
309 encodeURIComponent(this.$route.path);
310 this.conn = new WebSocket(this.connexionString);
311 this.conn.onopen = connectAndPoll;
312 this.conn.addEventListener("message", this.socketMessageListener);
313 this.socketCloseListener = setInterval(
315 if (this.conn.readyState == 3) {
316 this.conn.removeEventListener("message", this.socketMessageListener);
317 this.conn = new WebSocket(this.connexionString);
318 this.conn.addEventListener("message", this.socketMessageListener);
324 mounted: function() {
325 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
326 document.getElementById(eltName)
327 .addEventListener("click", processModalClick);
329 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
330 b.addEventListener("click", () => {
331 this.newchallenge.cadence = b.innerHTML;
334 const dispCorr = this.$route.query["disp"];
336 dispCorr || localStorage.getItem("type-challenges") || "live";
338 dispCorr || localStorage.getItem("type-games") || "live";
339 this.setDisplay('c', showCtype);
340 this.setDisplay('g', showGtype);
341 // Ask server for current corr games (all but mines)
343 // Also ask for corr challenges (open + sent by/to me)
344 // List them all, because they are not supposed to be that many (TODO?)
349 data: { uid: this.st.user.id },
350 success: (response) => {
352 response.challenges.length > 0 &&
353 this.challenges.length == 0 &&
354 this.cdisplay == "live"
357 .getElementById("btnCcorr")
358 .classList.add("somethingnew");
360 // Gather all senders names, and then retrieve full identity:
361 // (TODO [perf]: some might be online...)
363 response.challenges.forEach(c => {
364 if (c.uid != this.st.user.id) names[c.uid] = "";
365 else if (!!c.target && c.target != this.st.user.id)
366 names[c.target] = "";
368 const addChallenges = () => {
369 names[this.st.user.id] = this.st.user.name; //in case of
370 this.challenges = this.challenges.concat(
371 response.challenges.map(c => {
372 const from = { name: names[c.uid], id: c.uid }; //or just name
373 const type = this.classifyObject(c);
374 const vname = this.getVname(c.vid);
375 return Object.assign(
381 to: c.target ? names[c.target] : ""
388 if (Object.keys(names).length > 0) {
393 data: { ids: Object.keys(names).join(",") },
394 success: (response2) => {
395 response2.users.forEach(u => {
396 names[u.id] = u.name;
402 } else addChallenges();
407 beforeDestroy: function() {
408 this.cleanBeforeDestroy();
411 cleanBeforeDestroy: function() {
412 clearInterval(this.socketCloseListener);
413 document.removeEventListener('visibilitychange', this.visibilityChange);
414 window.removeEventListener('focus', this.onFocus);
415 window.removeEventListener('blur', this.onBlur);
416 window.removeEventListener("beforeunload", this.cleanBeforeDestroy);
417 this.conn.removeEventListener("message", this.socketMessageListener);
418 this.send("disconnect");
421 getRandomnessClass: function(pc) {
423 ["random-" + pc.randomness]: true
426 openModalPeople: function() {
427 window.doClick("modalPeople");
428 document.getElementById("inputChat").focus();
430 anonymousCount: function() {
432 Object.values(this.people).forEach(p => {
433 // Do not cound people who did not send their identity yet:
434 count += (!p.name && p.id === 0) ? 1 : 0;
438 visibilityChange: function() {
439 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
440 this.focus = (document.visibilityState == "visible");
441 this.send(this.focus ? "getfocus" : "losefocus");
443 onFocus: function() {
445 this.send("getfocus");
449 this.send("losefocus");
451 partialResetNewchallenge: function() {
452 // Reset potential target and custom FEN:
453 this.newchallenge.to = "";
454 this.newchallenge.fen = "";
455 this.newchallenge.diag = "";
456 this.newchallenge.memorize = false;
458 showNewchallengeForm: function() {
459 this.partialResetNewchallenge();
460 window.doClick("modalNewgame");
462 addPresetChall: function(chall) {
463 // Add only if not already existing:
464 if (this.presetChalls.some(c =>
465 c.vid == chall.vid &&
466 c.cadence == chall.cadence &&
467 c.randomness == chall.randomness
471 const L = this.presetChalls.length;
472 this.presetChalls.push({
475 vname: chall.vname, //redundant, but easier
476 cadence: chall.cadence,
477 randomness: chall.randomness
479 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
481 removePresetChall: function(e, pchall) {
484 this.presetChalls.findIndex(pc => pc.index == pchall.index);
485 this.presetChalls.splice(pchallIdx, 1);
486 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
488 tchallButtonsMargin: function() {
489 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
492 changeChallTarget: function() {
493 if (!this.newchallenge.to) {
494 // Reset potential FEN + diagram
495 this.newchallenge.fen = "";
496 this.newchallenge.diag = "";
499 cadenceFocusIfOpened: function() {
500 if (event.target.checked)
501 document.getElementById("cadence").focus();
503 send: function(code, obj) {
504 if (!!this.conn && this.conn.readyState == 1) {
505 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
508 getVname: function(vid) {
509 const variant = this.st.variants.find(v => v.id == vid);
510 // this.st.variants might be uninitialized (variant == null)
511 return variant ? variant.name : "";
513 filterChallenges: function(type) {
514 return this.challenges.filter(c => c.type == type);
516 filterGames: function(type) {
517 return this.games.filter(g => g.type == type);
519 // o: challenge or game
520 classifyObject: function(o) {
521 // Consider imports as live games (TODO)
522 if (!!o.id.match(/^i/)) return "live";
523 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
525 setDisplay: function(letter, type, e) {
526 this[letter + "display"] = type;
527 localStorage.setItem(
528 "type-" + (letter == "c" ? "challenges" : "games"),
533 : document.getElementById("btn" + letter.toUpperCase() + type);
534 elt.classList.add("active");
535 elt.classList.remove("somethingnew"); //in case of
536 if (!!elt.previousElementSibling)
537 elt.previousElementSibling.classList.remove("active");
538 else elt.nextElementSibling.classList.remove("active");
540 isGamer: function(sid) {
541 return Object.values(this.people[sid].tmpIds)
542 .some(v => v.focus && v.page.indexOf("/game/") >= 0);
544 isFocusedOnHall: function(sid) {
546 // This is meant to challenge people, thus the next 2 conditions:
547 this.st.user.id > 0 &&
548 sid != this.st.user.sid &&
549 Object.values(this.people[sid].tmpIds)
550 .some(v => v.focus && v.page == "/")
553 challenge: function(sid) {
554 this.partialResetNewchallenge();
555 // Available, in Hall
556 this.newchallenge.to = this.people[sid].name;
557 // TODO: also store target sid to not re-search for it
558 document.getElementById("modalPeople").checked = false;
559 window.doClick("modalNewgame");
561 watchGame: function(sid) {
562 // In some game, maybe playing maybe not: show a random one
564 Object.values(this.people[sid].tmpIds).forEach(v => {
566 const matchGid = v.page.match(/[a-zA-Z0-9]+$/);
567 if (!!matchGid) gids.push(matchGid[0]);
570 const gid = gids[Math.floor(Math.random() * gids.length)];
571 const game = this.games.find(g => g.id == gid);
572 if (!!game) this.showGame(game);
573 else this.$router.push("/game/" + gid); //game vs. me
575 showGame: function(g) {
576 // NOTE: we are an observer, since only games I don't play are shown here
577 // ==> Moves sent by connected remote player(s) if live game
578 this.$router.push("/game/" + g.id);
580 resetSocialColor: function() {
581 // TODO: this is called twice, once on opening an once on closing
582 document.getElementById("peopleBtn").classList.remove("somethingnew");
584 processChat: function(chat) {
585 this.send("newchat", { data: chat });
587 getOppsid: function(c) {
588 let oppsid = c.from.sid; //may not be defined if corr + offline opp
590 oppsid = Object.keys(this.people).find(
591 sid => this.people[sid].id == c.from.id
597 socketMessageListener: function(msg) {
598 if (!this.conn) return;
599 const data = JSON.parse(msg.data);
601 case "pollclientsandgamers": {
602 // TODO: shuffling and random filtering on server,
603 // if the room is really crowded.
604 Object.keys(data.sockIds).forEach(sid => {
605 if (sid != this.st.user.sid) {
606 // Pick a target tmpId (+page) at random:
607 const pt = Object.values(data.sockIds[sid]);
608 const randPage = pt[randInt(pt.length)].page;
617 if (!this.people[sid])
618 // Do not set name or id: identity unknown yet
619 this.people[sid] = { tmpIds: data.sockIds[sid] };
621 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
622 if (Object.values(data.sockIds[sid]).some(v => v.page == "/"))
624 this.send("askchallenges", { target: sid });
625 Object.values(data.sockIds[sid]).forEach(v => {
627 v.page.indexOf("/game/") >= 0 &&
628 !v.page.match(/\/[0-9]+$/)
630 // Peer is in Game: ask only if live game
631 this.send("askgame", { target: sid, page: v.page });
639 const page = data.page || "/";
640 if (data.code == "connect") {
641 // Ask challenges only on first connexion:
642 if (!this.people[data.from[0]])
643 this.send("askchallenges", { target: data.from[0] });
645 // Ask game only if live:
646 else if (!page.match(/\/[0-9]+$/))
647 this.send("askgame", { target: data.from[0], page: page });
648 if (!this.people[data.from[0]]) {
654 [data.from[1]]: { page: page, focus: true }
658 // For self multi-connects tests:
659 this.newConnect[data.from[0]] = true;
660 this.send("askidentity", { target: data.from[0], page: page });
662 this.people[data.from[0]].tmpIds[data.from[1]] =
663 { page: page, focus: true };
664 this.$forceUpdate(); //TODO: shouldn't be required
669 case "gdisconnect": {
670 // If the user reloads the page twice very quickly
671 // (experienced with Firefox), the first reload won't have time to
672 // connect but will trigger a "close" event anyway.
673 // ==> Next check is required.
674 if (!this.people[data.from[0]]) return;
675 delete this.people[data.from[0]].tmpIds[data.from[1]];
676 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
677 this.$delete(this.people, data.from[0]);
678 else this.$forceUpdate(); //TODO: shouldn't be required
679 if (data.code == "disconnect") {
680 // Remove the live challenges sent by this player:
683 c => c.type == "live" && c.from.sid == data.from[0],
687 // Remove the matching live game if now unreachable
688 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
689 // Corr games are always reachable:
690 if (!gid.match(/^[0-9]+$/)) {
691 // Live games are reachable if someone is on the game page
692 if (Object.values(this.people).every(p =>
693 Object.values(p.tmpIds).every(v => v.page != data.page))
695 ArrayFun.remove(this.games, g => g.id == gid);
702 let player = this.people[data.from[0]];
703 // If user reload a page, focus may arrive earlier than connect
705 player.tmpIds[data.from[1]].focus = true;
706 this.$forceUpdate(); //TODO: shouldn't be required
711 let player = this.people[data.from[0]];
713 player.tmpIds[data.from[1]].focus = false;
714 this.$forceUpdate(); //TODO: shouldn't be required
718 case "askidentity": {
719 // Request for identification
721 // Decompose to avoid revealing email
722 name: this.st.user.name,
723 sid: this.st.user.sid,
726 this.send("identity", { data: me, target: data.from });
730 const user = data.data;
731 let player = this.people[user.sid];
732 // player.tmpIds is already set
734 player.name = user.name;
735 // TODO: this.$set(people, ...) fails. So forceUpdate.
736 // But this shouldn't be like that!
738 // If I multi-connect, kill current connexion if no mark (I'm older)
739 if (this.newConnect[user.sid]) {
740 delete this.newConnect[user.sid];
743 user.id == this.st.user.id &&
744 user.sid != this.st.user.sid
746 // I logged in elsewhere:
747 this.cleanBeforeDestroy();
748 alert(this.st.tr["New connexion detected: tab now offline"]);
753 case "askchallenges": {
754 // Send my current live challenges (if any)
755 const myChallenges = this.challenges
757 c.from.sid == this.st.user.sid && c.type == "live"
760 // NOTE: in principle, should only send targeted challenge to the
761 // target. But we may not know yet the identity of the target
762 // (just name), so can't decide if data.from is the target.
765 from: this.st.user.sid,
767 randomness: c.randomness,
774 if (myChallenges.length > 0)
775 this.send("challenges", { data: myChallenges, target: data.from });
778 case "challenges": //after "askchallenges"
779 data.data.forEach(this.addChallenge);
782 this.addChallenge(data.data);
784 case "refusechallenge": {
785 const cid = data.data;
786 ArrayFun.remove(this.challenges, c => c.id == cid);
787 alert(this.st.tr["Challenge declined"]);
790 case "deletechallenge_s": {
791 // NOTE: the challenge(s) may be already removed
792 const cref = data.data;
794 ArrayFun.remove(this.challenges, c => c.id == cref.cid);
795 else if (!!cref.sids) {
796 cref.sids.forEach(s => {
799 c => c.type == "live" && c.from.sid == s,
806 case "game": // Individual request
808 const game = data.data;
809 // Ignore games where I play (will go in MyGames page),
810 // and also games that I already received.
812 game.players.every(p =>
813 p.sid != this.st.user.sid && p.id != this.st.user.id) &&
814 this.games.findIndex(g => g.id == game.id) == -1
817 newGame.type = this.classifyObject(game);
818 newGame.vname = this.getVname(game.vid);
820 // New game from Hall
822 this.games.push(newGame);
824 (newGame.type == "live" && this.gdisplay == "corr") ||
825 (newGame.type == "corr" && this.gdisplay == "live")
828 .getElementById("btnG" + newGame.type)
829 .classList.add("somethingnew");
835 let g = this.games.find(g => g.id == data.gid);
836 if (!!g) g.score = data.score;
840 // New game just started, I'm involved
841 const gameInfo = data.data;
842 if (this.classifyObject(gameInfo) == "live")
843 this.startNewGame(gameInfo);
846 this.st.tr["New correspondance game:"] + " " +
847 "<a href='#/game/" + gameInfo.id + "'>" +
848 "#/game/" + gameInfo.id + "</a>";
849 document.getElementById("modalInfo").checked = true;
854 this.$refs["chatcomp"].newChat(data.data);
855 if (!document.getElementById("modalPeople").checked)
856 document.getElementById("peopleBtn").classList.add("somethingnew");
860 loadMoreCorr: function() {
866 uid: this.st.user.id,
870 const L = res.games.length;
873 this.cursor == Number.MAX_SAFE_INTEGER &&
874 this.games.length == 0 &&
875 this.gdisplay == "live"
877 // First loading: show indicators
879 .getElementById("btnGcorr")
880 .classList.add("somethingnew");
882 this.cursor = res.games[L - 1].created;
883 let moreGames = res.games.map(g => {
884 const vname = this.getVname(g.vid);
885 return Object.assign(
894 this.games = this.games.concat(moreGames);
895 } else this.hasMore = false;
900 // Challenge lifecycle:
901 addChallenge: function(chall) {
902 // NOTE about next condition: see "askchallenges" case.
905 (this.people[chall.from].id > 0 &&
906 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
908 let newChall = Object.assign({}, chall);
909 newChall.type = this.classifyObject(chall);
910 newChall.randomness = chall.randomness;
911 newChall.added = Date.now();
912 let fromValues = Object.assign({}, this.people[chall.from]);
913 delete fromValues["pages"]; //irrelevant in this context
914 newChall.from = Object.assign({ sid: chall.from }, fromValues);
915 newChall.vname = this.getVname(newChall.vid);
916 this.challenges.push(newChall);
918 (newChall.type == "live" && this.cdisplay == "corr") ||
919 (newChall.type == "corr" && this.cdisplay == "live")
922 .getElementById("btnC" + newChall.type)
923 .classList.add("somethingnew");
928 // fromValues.name should exist since the player is online, but
929 // let's consider there is some chance that the challenge arrives
930 // right after we connected and before receiving the poll result:
931 { body: "from " + (fromValues.name || "unknown yet...") }
936 loadNewchallVariant: async function(cb) {
937 const vname = this.getVname(this.newchallenge.vid);
938 await import("@/variants/" + vname + ".js")
940 window.V = vModule[vname + "Rules"];
941 this.newchallenge.V = window.V;
942 this.newchallenge.vname = vname;
946 trySetNewchallDiag: function() {
947 if (!this.newchallenge.fen) {
948 this.newchallenge.diag = "";
951 // If vid > 0 then the variant is loaded (function above):
952 window.V = this.newchallenge.V;
954 this.newchallenge.vid > 0 &&
955 !!this.newchallenge.fen &&
956 V.IsGoodFen(this.newchallenge.fen)
958 const parsedFen = V.ParseFen(this.newchallenge.fen);
959 this.newchallenge.diag = getDiagram({
960 position: parsedFen.position,
961 orientation: parsedFen.turn
963 } else this.newchallenge.diag = "";
965 newChallFromPreset(pchall) {
966 this.partialResetNewchallenge();
967 this.newchallenge.vid = pchall.vid;
968 this.newchallenge.cadence = pchall.cadence;
969 this.newchallenge.randomness = pchall.randomness;
970 this.loadNewchallVariant(this.issueNewChallenge);
972 issueNewChallenge: async function() {
973 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
974 this.newchallenge.cadence += "+0"; //assume minutes, no increment
975 const ctype = this.classifyObject(this.newchallenge);
976 // TODO: cadence still unchecked so ctype could be wrong...
978 if (!this.newchallenge.vid)
979 error = this.st.tr["Please select a variant"];
980 else if (ctype == "corr" && this.st.user.id <= 0)
981 error = this.st.tr["Please log in to play correspondance games"];
982 else if (!!this.newchallenge.to) {
983 if (this.newchallenge.to == this.st.user.name)
984 error = this.st.tr["Self-challenge is forbidden"];
987 Object.values(this.people).every(p => p.name != this.newchallenge.to)
989 error = this.newchallenge.to + " " + this.st.tr["is not online"];
996 window.V = this.newchallenge.V;
997 error = checkChallenge(this.newchallenge);
1002 // NOTE: "from" information is not required here
1003 let chall = Object.assign({}, this.newchallenge);
1004 // Add only if not already issued (not counting target or FEN):
1005 if (this.challenges.some(c =>
1006 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
1007 c.vid == chall.vid &&
1008 c.cadence == chall.cadence &&
1009 c.randomness == chall.randomness
1011 alert(this.st.tr["Challenge already exists"]);
1014 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
1016 delete chall["diag"];
1017 const finishAddChallenge = cid => {
1018 chall.id = cid || "c" + getRandString();
1019 const MAX_ALLOWED_CHALLS = 3;
1020 // Remove oldest challenge if 3 found: only 3 at a time of a given type
1021 let countMyChalls = 0;
1022 let challToDelIdx = 0;
1023 let oldestAdded = Number.MAX_SAFE_INTEGER;
1024 for (let i=0; i<this.challenges.length; i++) {
1025 const c = this.challenges[i];
1028 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
1031 if (c.added < oldestAdded) {
1033 oldestAdded = c.added;
1037 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1039 "deletechallenge_s",
1040 { data: { cid: this.challenges[challToDelIdx].id } }
1042 if (ctype == "corr") {
1046 { data: { id: this.challenges[challToDelIdx].id } }
1049 this.challenges.splice(challToDelIdx, 1);
1051 this.send("newchallenge", {
1052 data: Object.assign({ from: this.st.user.sid }, chall)
1054 // Add new challenge:
1056 sid: this.st.user.sid,
1057 id: this.st.user.id,
1058 name: this.st.user.name
1060 chall.added = Date.now();
1061 // NOTE: vname and type are redundant (deduced from cadence + vid)
1063 chall.vname = this.newchallenge.vname;
1064 this.challenges.push(chall);
1065 // Remember cadence + vid for quicker further challenges:
1066 localStorage.setItem("cadence", chall.cadence);
1067 localStorage.setItem("vid", chall.vid);
1068 localStorage.setItem("challRandomness", chall.randomness);
1069 document.getElementById("modalNewgame").checked = false;
1070 // Show the challenge if not on current display
1072 (ctype == "live" && this.cdisplay == "corr") ||
1073 (ctype == "corr" && this.cdisplay == "live")
1075 this.setDisplay('c', ctype);
1078 if (ctype == "live") {
1079 // Live challenges have a random ID
1080 finishAddChallenge(null);
1082 // Correspondance game: send challenge to server
1087 data: { chall: chall },
1088 success: (response) => {
1089 finishAddChallenge(response.id);
1095 // Callback function after a diagram was showed to accept
1096 // or refuse targetted challenge:
1097 decisionChallenge: function(accepted) {
1098 this.curChallToAccept.accepted = accepted;
1099 this.finishProcessingChallenge(this.curChallToAccept);
1100 document.getElementById("modalAccept").checked = false;
1102 finishProcessingChallenge: function(c) {
1105 sid: this.st.user.sid,
1106 id: this.st.user.id,
1107 name: this.st.user.name
1110 if (c.type == "live") {
1111 // Remove all live challenges of both players
1113 "deletechallenge_s",
1114 { data: { sids: [c.from.sid, c.seat.sid] } }
1118 // Corr challenge: just remove the challenge
1119 this.send("deletechallenge_s", { data: { cid: c.id } });
1121 const oppsid = this.getOppsid(c);
1123 this.send("refusechallenge", { data: c.id, target: oppsid });
1124 if (c.type == "corr") {
1128 { data: { id: c.id } }
1131 this.send("deletechallenge_s", { data: { cid: c.id } });
1134 // TODO: if several players click same challenge at the same time: problem
1135 clickChallenge: async function(c) {
1137 c.from.sid == this.st.user.sid || //live
1138 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1140 if (c.type == "corr" && this.st.user.id <= 0) {
1141 alert(this.st.tr["Please log in to accept corr challenges"]);
1145 await import("@/variants/" + c.vname + ".js")
1146 .then((vModule) => {
1147 window.V = vModule[c.vname + "Rules"];
1149 // c.to == this.st.user.name (connected)
1151 const parsedFen = V.ParseFen(c.fen);
1152 c.mycolor = V.GetOppCol(parsedFen.turn);
1153 this.tchallDiag = getDiagram({
1154 position: parsedFen.position,
1155 orientation: c.mycolor
1158 this.curChallToAccept = c;
1159 document.getElementById("modalAccept").checked = true;
1161 else this.finishProcessingChallenge(c);
1166 if (c.type == "corr") {
1170 { data: { id: c.id } }
1173 this.send("deletechallenge_s", { data: { cid: c.id } });
1175 // In all cases, the challenge is consumed:
1176 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1178 // NOTE: when launching game, the challenge is already being deleted
1179 launchGame: function(c) {
1180 // White player index 0, black player index 1:
1183 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1184 : shuffle([c.from, c.seat]);
1185 // These game informations will be shared
1187 id: getRandString(),
1188 fen: c.fen || V.GenRandInitFen(c.randomness),
1189 randomness: c.randomness, //for rematch
1194 const notifyNewgame = () => {
1195 const oppsid = this.getOppsid(c);
1197 // Opponent is online
1198 this.send("startgame", { data: gameInfo, target: oppsid });
1199 // If new corr game, notify Hall (except opponent and me)
1200 if (c.type == "corr") {
1205 excluded: [this.st.user.sid, oppsid]
1209 // Notify MyGames page:
1214 targets: gameInfo.players
1217 // NOTE: no need to send the game to the room, since I'll connect
1218 // on game just after, the main Hall will be notified.
1220 if (c.type == "live") {
1222 this.startNewGame(gameInfo);
1224 // corr: game only on server
1229 // cid is useful to delete the challenge:
1234 success: (response) => {
1235 gameInfo.id = response.id;
1237 this.$router.push("/game/" + response.id);
1243 // NOTE: for live games only (corr games start on the server)
1244 startNewGame: function(gameInfo) {
1245 const game = Object.assign(
1249 // (other) Game infos: constant
1250 fenStart: gameInfo.fen,
1251 vname: this.getVname(gameInfo.vid),
1252 created: Date.now(),
1253 // Game state (including FEN): will be updated
1255 clocks: [-1, -1], //-1 = unstarted
1262 const myIdx = (game.players[0].sid == this.st.user.sid ? 0 : 1);
1263 GameStorage.add(game, (err) => {
1264 // If an error occurred, game is not added: a tab already
1265 // added the game. Maybe a focused one, maybe not.
1266 // We know for sure that it emitted the gong start sound.
1267 // ==> Do not play it again.
1268 if (!err && this.st.settings.sound)
1269 new Audio("/sounds/newgame.flac").play().catch(() => {});
1273 { body: "vs " + game.players[1-myIdx].name || "@nonymous" }
1276 this.$router.push("/game/" + gameInfo.id);
1279 this.focus ? 500 + 1000 * Math.random() : 0
1286 <style lang="sass" scoped>
1294 #newgameDiv > .card, #acceptDiv > .card
1298 div#peopleWrap > .card
1301 @media screen and (min-width: 1281px)
1302 div#peopleWrap > .card
1305 @media screen and (max-width: 1280px)
1306 div#peopleWrap > .card
1309 @media screen and (max-width: 767px)
1310 div#peopleWrap > .card
1323 @media screen and (max-width: 767px)
1338 button.player-action
1342 background-color: #c5fefe !important
1345 background-color: #f9faee
1348 background-color: lightgreen
1350 background-color: red
1353 // margin-top set dynamically (depends if diagram showed or not)
1364 // width: 100% required for Firefox
1372 @media screen and (max-width: 767px)
1378 background-color: #FF5733
1380 background-color: #2B63B4
1382 background-color: #33B42B
1384 @media screen and (max-width: 767px)
1393 background-color: lightgrey