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(v-model="newchallenge.to")
79 v-for="p in Object.values(people)"
85 v-model="newchallenge.to"
87 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
90 @input="trySetNewchallDiag()"
92 v-model="newchallenge.fen"
94 .diagram(v-html="newchallenge.diag")
95 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
96 input#modalPeople.modal(
98 @click="resetSocialColor()"
102 data-checkbox="modalPeople"
105 label.modal-close(for="modalPeople")
109 v-for="sid in Object.keys(people)"
110 v-if="!!people[sid].name"
112 span {{ people[sid].name }}
113 button.player-action(
115 @click="watchGame(sid)"
117 | {{ st.tr["Observe"] }}
118 button.player-action(
119 v-else-if="isFocusedOnHall(sid)"
120 @click="challenge(sid)"
122 | {{ st.tr["Challenge"] }}
123 p.anonymous @nonymous ({{ anonymousCount }})
127 @mychat="processChat"
132 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
134 button#peopleBtn(onClick="window.doClick('modalPeople')")
135 | {{ st.tr["Who's there?"] }}
136 button(@click="showNewchallengeForm()")
137 | {{ st.tr["New game"] }}
138 .row(v-if="presetChalls.length > 0")
139 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
140 h4.text-center {{ st.tr["Preset challenges"] }}
144 th {{ st.tr["Variant"] }}
145 th {{ st.tr["Cadence"] }}
146 th {{ st.tr["Random?"] }}
150 v-for="pc in presetChalls"
151 @click="newChallFromPreset(pc)"
155 td(:class="getRandomnessClass(pc)")
156 td.remove-preset(@click="removePresetChall($event, pc)")
157 img(src="/images/icons/delete.svg")
159 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
162 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
163 | {{ st.tr["Live challenges"] }}
164 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
165 | {{ st.tr["Correspondance challenges"] }}
167 v-show="cdisplay=='live'"
168 :challenges="filterChallenges('live')"
169 @click-challenge="clickChallenge"
172 v-show="cdisplay=='corr'"
173 :challenges="filterChallenges('corr')"
174 @click-challenge="clickChallenge"
178 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
179 | {{ st.tr["Live games"] }}
180 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
181 | {{ st.tr["Correspondance games"] }}
183 v-show="gdisplay=='live'"
184 :games="filterGames('live')"
186 @show-game="showGame"
188 div(v-show="gdisplay=='corr'")
190 :games="filterGames('corr')"
192 @show-game="showGame"
198 | {{ st.tr["Load more"] }}
202 import { store } from "@/store";
203 import { checkChallenge } from "@/data/challengeCheck";
204 import { ArrayFun } from "@/utils/array";
205 import { ajax } from "@/utils/ajax";
206 import params from "@/parameters";
207 import { getRandString, shuffle } from "@/utils/alea";
208 import { getDiagram } from "@/utils/printDiagram";
209 import Chat from "@/components/Chat.vue";
210 import GameList from "@/components/GameList.vue";
211 import ChallengeList from "@/components/ChallengeList.vue";
212 import { GameStorage } from "@/utils/gameStorage";
213 import { processModalClick } from "@/utils/modalClick";
224 cdisplay: "live", //or corr
226 // timestamp of last showed (oldest) corr game:
227 cursor: Number.MAX_SAFE_INTEGER,
228 // hasMore == TRUE: a priori there could be more games to load
236 vid: parseInt(localStorage.getItem("vid")) || 0,
237 to: "", //name of challenged player (if any)
238 cadence: localStorage.getItem("cadence") || "",
239 randomness: parseInt(localStorage.getItem("challRandomness")) || 2,
240 // VariantRules object, stored to not interfere with
241 // diagrams of targetted challenges:
244 diag: "", //visualizing FEN
245 memorize: false //put settings in localStorage
248 curChallToAccept: {from: {}},
249 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
253 // Related to (killing of) self multi-connects:
259 // st.variants changes only once, at loading from [] to [...]
260 "st.variants": function() {
261 // Set potential challenges and games variant names:
262 this.challenges.concat(this.games).forEach(o => {
263 if (!o.vname) o.vname = this.getVname(o.vid);
265 if (!this.newchallenge.V && this.newchallenge.vid > 0)
266 this.loadNewchallVariant();
270 anonymousCount: function() {
272 Object.values(this.people).forEach(p => {
273 // Do not cound people who did not send their identity yet:
274 count += (!p.name && p.id === 0) ? 1 : 0;
279 created: function() {
280 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
281 this.loadNewchallVariant();
282 const my = this.st.user;
289 pages: [{ path: "/", focus: true }]
292 const connectAndPoll = () => {
293 this.send("connect");
294 this.send("pollclientsandgamers");
296 // Initialize connection
297 this.connexionString =
306 // Hall: path is "/" (could be hard-coded as well)
307 encodeURIComponent(this.$route.path);
308 this.conn = new WebSocket(this.connexionString);
309 this.conn.onopen = connectAndPoll;
310 this.conn.onmessage = this.socketMessageListener;
311 this.conn.onclose = this.socketCloseListener;
313 mounted: function() {
314 document.addEventListener('visibilitychange', this.visibilityChange);
315 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
316 document.getElementById(eltName)
317 .addEventListener("click", processModalClick);
319 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
320 b.addEventListener("click", () => {
321 this.newchallenge.cadence = b.innerHTML;
324 const dispCorr = this.$route.query["disp"];
326 dispCorr || localStorage.getItem("type-challenges") || "live";
328 dispCorr || localStorage.getItem("type-games") || "live";
329 this.setDisplay('c', showCtype);
330 this.setDisplay('g', showGtype);
331 // Ask server for current corr games (all but mines)
337 uid: this.st.user.id,
340 success: (response) => {
341 const L = response.games.length;
343 this.cursor = response.games[L - 1].created;
344 if (this.games.length == 0 && this.gdisplay == "live") {
346 .getElementById("btnGcorr")
347 .classList.add("somethingnew");
350 this.games = this.games.concat(
351 response.games.map(g => {
352 const vname = this.getVname(g.vid);
353 return Object.assign(
366 // Also ask for corr challenges (open + sent by/to me)
371 data: { uid: this.st.user.id },
372 success: (response) => {
374 response.challenges.length > 0 &&
375 this.challenges.length == 0 &&
376 this.cdisplay == "live"
379 .getElementById("btnCcorr")
380 .classList.add("somethingnew");
382 // Gather all senders names, and then retrieve full identity:
383 // (TODO [perf]: some might be online...)
385 response.challenges.forEach(c => {
386 if (c.uid != this.st.user.id) names[c.uid] = "";
387 else if (!!c.target && c.target != this.st.user.id)
388 names[c.target] = "";
390 const addChallenges = () => {
391 names[this.st.user.id] = this.st.user.name; //in case of
392 this.challenges = this.challenges.concat(
393 response.challenges.map(c => {
394 const from = { name: names[c.uid], id: c.uid }; //or just name
395 const type = this.classifyObject(c);
396 const vname = this.getVname(c.vid);
397 return Object.assign(
403 to: c.target ? names[c.target] : ""
410 if (Object.keys(names).length > 0) {
415 data: { ids: Object.keys(names).join(",") },
416 success: (response2) => {
417 response2.users.forEach(u => {
418 names[u.id] = u.name;
424 } else addChallenges();
429 beforeDestroy: function() {
430 document.removeEventListener('visibilitychange', this.visibilityChange);
431 this.send("disconnect");
434 getRandomnessClass: function(pc) {
436 ["random-" + pc.randomness]: true
439 visibilityChange: function() {
440 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
442 document.visibilityState == "visible"
447 partialResetNewchallenge: function() {
448 // Reset potential target and custom FEN:
449 this.newchallenge.to = "";
450 this.newchallenge.fen = "";
451 this.newchallenge.diag = "";
452 this.newchallenge.memorize = false;
454 showNewchallengeForm: function() {
455 this.partialResetNewchallenge();
456 window.doClick("modalNewgame");
458 addPresetChall: function(chall) {
459 // Add only if not already existing:
460 if (this.presetChalls.some(c =>
461 c.vid == chall.vid &&
462 c.cadence == chall.cadence &&
463 c.randomness == chall.randomness
467 const L = this.presetChalls.length;
468 this.presetChalls.push({
471 vname: chall.vname, //redundant, but easier
472 cadence: chall.cadence,
473 randomness: chall.randomness
475 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
477 removePresetChall: function(e, pchall) {
479 const pchallIdx = this.presetChalls.findIndex(pc => pc.index == pchall.index);
480 this.presetChalls.splice(pchallIdx, 1);
481 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
483 tchallButtonsMargin: function() {
484 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
487 cadenceFocusIfOpened: function() {
488 if (event.target.checked)
489 document.getElementById("cadence").focus();
491 send: function(code, obj) {
493 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
496 getVname: function(vid) {
497 const variant = this.st.variants.find(v => v.id == vid);
498 // this.st.variants might be uninitialized (variant == null)
499 return variant ? variant.name : "";
501 filterChallenges: function(type) {
502 return this.challenges.filter(c => c.type == type);
504 filterGames: function(type) {
505 return this.games.filter(g => g.type == type);
507 classifyObject: function(o) {
508 // o: challenge or game
509 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
511 setDisplay: function(letter, type, e) {
512 this[letter + "display"] = type;
513 localStorage.setItem(
514 "type-" + (letter == "c" ? "challenges" : "games"),
519 : document.getElementById("btn" + letter.toUpperCase() + type);
520 elt.classList.add("active");
521 elt.classList.remove("somethingnew"); //in case of
522 if (!!elt.previousElementSibling)
523 elt.previousElementSibling.classList.remove("active");
524 else elt.nextElementSibling.classList.remove("active");
526 isGamer: function(sid) {
527 return this.people[sid].pages
528 .some(p => p.focus && p.path.indexOf("/game/") >= 0);
530 isFocusedOnHall: function(sid) {
532 // This is meant to challenge people, thus the next 2 conditions:
533 this.st.user.id > 0 &&
534 sid != this.st.user.sid &&
535 this.people[sid].pages.some(p => p.path == "/" && p.focus)
538 challenge: function(sid) {
539 this.partialResetNewchallenge();
540 // Available, in Hall
541 this.newchallenge.to = this.people[sid].name;
542 // TODO: also store target sid to not re-search for it
543 document.getElementById("modalPeople").checked = false;
544 window.doClick("modalNewgame");
546 watchGame: function(sid) {
547 // In some game, maybe playing maybe not: show a random one
549 this.people[sid].pages.forEach(p => {
551 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
552 if (!!matchGid) gids.push(matchGid[0]);
555 const gid = gids[Math.floor(Math.random() * gids.length)];
556 const game = this.games.find(g => g.id == gid);
557 if (!!game) this.showGame(game);
558 else this.$router.push("/game/" + gid); //game vs. me
560 showGame: function(g) {
561 // NOTE: we are an observer, since only games I don't play are shown here
562 // ==> Moves sent by connected remote player(s) if live game
563 let url = "/game/" + g.id;
564 if (g.type == "live")
565 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
566 this.$router.push(url);
568 resetSocialColor: function() {
569 // TODO: this is called twice, once on opening an once on closing
570 document.getElementById("peopleBtn").classList.remove("somethingnew");
572 processChat: function(chat) {
573 this.send("newchat", { data: chat });
575 getOppsid: function(c) {
576 let oppsid = c.from.sid; //may not be defined if corr + offline opp
578 oppsid = Object.keys(this.people).find(
579 sid => this.people[sid].id == c.from.id
585 socketMessageListener: function(msg) {
586 if (!this.conn) return;
587 const data = JSON.parse(msg.data);
589 case "pollclientsandgamers": {
590 // Since people can be both in Hall and Game,
591 // need to track "askIdentity" requests:
592 let identityAsked = {};
593 data.sockIds.forEach(s => {
594 const page = s.page || "/";
595 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
596 this.send("askidentity", { target: s.sid, page: page });
597 identityAsked[s.sid] = true;
599 if (!this.people[s.sid]) {
600 // Do not set name or id: identity unknown yet
601 this.people[s.sid] = { pages: [{path: page, focus: true}] };
603 else if (!(this.people[s.sid].pages.find(p => p.path == page)))
604 this.people[s.sid].pages.push({ path: page, focus: true });
607 this.send("askchallenges", { target: s.sid });
608 // Peer is in Game: ask only if live game
609 else if (!page.match(/\/[0-9]+$/))
610 this.send("askgame", { target: s.sid, page: page });
616 const page = data.page || "/";
617 // Only ask game / challenges if first connexion:
618 if (!this.people[data.from]) {
619 this.people[data.from] = { pages: [{ path: page, focus: true }] };
620 if (data.code == "connect")
621 this.send("askchallenges", { target: data.from });
622 // Ask game only if live:
623 else if (!page.match(/\/[0-9]+$/))
624 this.send("askgame", { target: data.from, page: page });
626 // Append page if not already in list
627 if (!(this.people[data.from].pages.find(p => p.path == page)))
628 this.people[data.from].pages.push({ path: page, focus: true });
630 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
631 // Identity not known yet
632 this.newConnect[data.from] = true; //for self multi-connects tests
633 this.send("askidentity", { target: data.from, page: page });
638 case "gdisconnect": {
639 // If the user reloads the page twice very quickly (experienced with Firefox),
640 // the first reload won't have time to connect but will trigger a "close" event anyway.
641 // ==> Next check is required.
642 if (!this.people[data.from]) return;
643 // Disconnect means no more tmpIds:
644 if (data.code == "disconnect") {
645 // Remove the live challenges sent by this player:
648 c => c.type == "live" && c.from.sid == data.from,
652 // Remove the matching live game if now unreachable
653 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
654 // Corr games are always reachable:
655 if (!gid.match(/^[0-9]+$/)) {
656 const gidx = this.games.findIndex(g => g.id == gid);
657 // NOTE: gidx should always be >= 0 (TODO?)
659 const game = this.games[gidx];
660 ArrayFun.remove(game.rids, rid => rid == data.from);
661 if (game.rids.length == 0) this.games.splice(gidx, 1);
665 const page = data.page || "/";
666 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
667 if (this.people[data.from].pages.length == 0)
668 this.$delete(this.people, data.from);
672 // If user reload a page, focus may arrive earlier than connect
673 if (!!this.people[data.from]) {
674 this.people[data.from].pages
675 .find(p => p.path == data.page).focus = true;
676 this.$forceUpdate(); //TODO: shouldn't be required
680 if (!!this.people[data.from]) {
681 this.people[data.from].pages
682 .find(p => p.path == data.page).focus = false;
683 this.$forceUpdate(); //TODO: shouldn't be required
687 // I logged in elsewhere:
689 alert(this.st.tr["New connexion detected: tab now offline"]);
691 case "askidentity": {
692 // Request for identification
694 // Decompose to avoid revealing email
695 name: this.st.user.name,
696 sid: this.st.user.sid,
699 this.send("identity", { data: me, target: data.from });
703 const user = data.data;
704 let player = this.people[user.sid];
705 // player.pages is already set
707 player.name = user.name;
708 // TODO: this.$set(people, ...) fails. So forceUpdate.
709 // But this shouldn't be like that!
711 // If I multi-connect, kill current connexion if no mark (I'm older)
712 if (this.newConnect[user.sid]) {
715 user.id == this.st.user.id &&
716 user.sid != this.st.user.sid &&
717 !this.killed[this.st.user.sid]
719 this.send("killme", { sid: this.st.user.sid });
720 this.killed[this.st.user.sid] = true;
722 delete this.newConnect[user.sid];
726 case "askchallenges": {
727 // Send my current live challenges (if any)
728 const myChallenges = this.challenges
730 c.from.sid == this.st.user.sid && c.type == "live"
733 // NOTE: in principle, should only send targeted challenge to the target.
734 // But we may not know yet the identity of the target (just name),
735 // so cannot decide if data.from is the target or not.
738 from: this.st.user.sid,
740 randomness: c.randomness,
747 if (myChallenges.length > 0)
748 this.send("challenges", { data: myChallenges, target: data.from });
751 case "challenges": //after "askchallenges"
752 data.data.forEach(this.addChallenge);
755 this.addChallenge(data.data);
757 case "refusechallenge": {
758 const cid = data.data;
759 ArrayFun.remove(this.challenges, c => c.id == cid);
760 alert(this.st.tr["Challenge declined"]);
763 case "deletechallenge_s": {
764 // NOTE: the challenge(s) may be already removed
765 const cref = data.data;
766 if (!!cref.cid) ArrayFun.remove(this.challenges, c => c.id == cref.cid);
767 else if (!!cref.sids) {
768 cref.sids.forEach(s => {
771 c => c.type == "live" && c.from.sid == s,
778 case "game": // Individual request
780 const game = data.data;
781 // Ignore games where I play (will go in MyGames page)
782 if (game.players.every(p =>
783 p.sid != this.st.user.sid && p.id != this.st.user.id))
785 let locGame = this.games.find(g => g.id == game.id);
788 newGame.type = this.classifyObject(game);
789 newGame.vname = this.getVname(game.vid);
791 // New game from Hall
793 newGame.rids = [game.rid];
794 delete newGame["rid"];
795 this.games.push(newGame);
797 (newGame.type == "live" && this.gdisplay == "corr") ||
798 (newGame.type == "corr" && this.gdisplay == "live")
801 .getElementById("btnG" + newGame.type)
802 .classList.add("somethingnew");
805 // Append rid (if not already in list)
806 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
812 let g = this.games.find(g => g.id == data.gid);
813 if (!!g) g.score = data.score;
817 // New game just started, I'm involved
818 const gameInfo = data.data;
819 if (this.classifyObject(gameInfo) == "live")
820 this.startNewGame(gameInfo);
823 this.st.tr["New correspondance game:"] +
824 " <a href='#/game/" +
830 document.getElementById("modalInfo").checked = true;
835 this.newChat = data.data;
836 if (!document.getElementById("modalPeople").checked)
837 document.getElementById("peopleBtn").classList.add("somethingnew");
841 socketCloseListener: function() {
842 if (!this.conn) return;
843 this.conn = new WebSocket(this.connexionString);
844 this.conn.addEventListener("message", this.socketMessageListener);
845 this.conn.addEventListener("close", this.socketCloseListener);
847 loadMore: function() {
853 uid: this.st.user.id,
857 if (res.games.length > 0) {
858 const L = res.games.length;
859 this.cursor = res.games[L - 1].created;
860 let moreGames = res.games.map(g => {
861 const vname = this.getVname(g.vid);
862 return Object.assign(
871 this.games = this.games.concat(moreGames);
872 } else this.hasMore = false;
877 // Challenge lifecycle:
878 addChallenge: function(chall) {
879 // NOTE about next condition: see "askchallenges" case.
882 (this.people[chall.from].id > 0 &&
883 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
885 let newChall = Object.assign({}, chall);
886 newChall.type = this.classifyObject(chall);
887 newChall.randomness = chall.randomness;
888 newChall.added = Date.now();
889 let fromValues = Object.assign({}, this.people[chall.from]);
890 delete fromValues["pages"]; //irrelevant in this context
891 newChall.from = Object.assign({ sid: chall.from }, fromValues);
892 newChall.vname = this.getVname(newChall.vid);
893 this.challenges.push(newChall);
895 (newChall.type == "live" && this.cdisplay == "corr") ||
896 (newChall.type == "corr" && this.cdisplay == "live")
899 .getElementById("btnC" + newChall.type)
900 .classList.add("somethingnew");
904 loadNewchallVariant: async function(cb) {
905 const vname = this.getVname(this.newchallenge.vid);
906 const vModule = await import("@/variants/" + vname + ".js");
907 this.newchallenge.V = vModule.VariantRules;
908 this.newchallenge.vname = vname;
911 trySetNewchallDiag: function() {
912 if (!this.newchallenge.fen) {
913 this.newchallenge.diag = "";
916 // If vid > 0 then the variant is loaded (function above):
917 window.V = this.newchallenge.V;
919 this.newchallenge.vid > 0 &&
920 !!this.newchallenge.fen &&
921 V.IsGoodFen(this.newchallenge.fen)
923 const parsedFen = V.ParseFen(this.newchallenge.fen);
924 this.newchallenge.diag = getDiagram({
925 position: parsedFen.position,
926 orientation: parsedFen.turn
930 newChallFromPreset(pchall) {
931 this.partialResetNewchallenge();
932 this.newchallenge.vid = pchall.vid;
933 this.newchallenge.cadence = pchall.cadence;
934 this.newchallenge.randomness = pchall.randomness;
935 this.loadNewchallVariant(this.issueNewChallenge);
937 issueNewChallenge: async function() {
938 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
939 this.newchallenge.cadence += "+0"; //assume minutes, no increment
940 const ctype = this.classifyObject(this.newchallenge);
941 // TODO: cadence still unchecked so ctype could be wrong...
943 if (!this.newchallenge.vid)
944 error = this.st.tr["Please select a variant"];
945 else if (ctype == "corr" && this.st.user.id <= 0)
946 error = this.st.tr["Please log in to play correspondance games"];
947 else if (!!this.newchallenge.to) {
948 if (this.newchallenge.to == this.st.user.name)
949 error = this.st.tr["Self-challenge is forbidden"];
952 Object.values(this.people).every(p => p.name != this.newchallenge.to)
954 error = this.newchallenge.to + " " + this.st.tr["is not online"];
961 window.V = this.newchallenge.V;
962 error = checkChallenge(this.newchallenge);
967 // NOTE: "from" information is not required here
968 let chall = Object.assign({}, this.newchallenge);
969 // Add only if not already issued (not counting target or FEN):
970 if (this.challenges.some(c =>
971 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
972 c.vid == chall.vid &&
973 c.cadence == chall.cadence &&
974 c.randomness == chall.randomness
976 alert(this.st.tr["Challenge already exists"]);
979 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
981 delete chall["diag"];
982 const finishAddChallenge = cid => {
983 chall.id = cid || "c" + getRandString();
984 const MAX_ALLOWED_CHALLS = 3;
985 // Remove oldest challenge if 3 found: only 3 at a time of a given type
986 let countMyChalls = 0;
987 let challToDelIdx = 0;
988 let oldestAdded = Number.MAX_SAFE_INTEGER;
989 for (let i=0; i<this.challenges.length; i++) {
990 const c = this.challenges[i];
993 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
996 if (c.added < oldestAdded) {
998 oldestAdded = c.added;
1002 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1004 "deletechallenge_s",
1005 { data: { cid: this.challenges[challToDelIdx].id } }
1007 if (ctype == "corr") {
1011 { data: { id: this.challenges[challToDelIdx].id } }
1014 this.challenges.splice(challToDelIdx, 1);
1016 this.send("newchallenge", {
1017 data: Object.assign({ from: this.st.user.sid }, chall)
1019 // Add new challenge:
1021 sid: this.st.user.sid,
1022 id: this.st.user.id,
1023 name: this.st.user.name
1025 chall.added = Date.now();
1026 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
1028 chall.vname = this.newchallenge.vname;
1029 this.challenges.push(chall);
1030 // Remember cadence + vid for quicker further challenges:
1031 localStorage.setItem("cadence", chall.cadence);
1032 localStorage.setItem("vid", chall.vid);
1033 localStorage.setItem("challRandomness", chall.randomness);
1034 document.getElementById("modalNewgame").checked = false;
1035 // Show the challenge if not on current display
1037 (ctype == "live" && this.cdisplay == "corr") ||
1038 (ctype == "corr" && this.cdisplay == "live")
1040 this.setDisplay('c', ctype);
1043 if (ctype == "live") {
1044 // Live challenges have a random ID
1045 finishAddChallenge(null);
1047 // Correspondance game: send challenge to server
1052 data: { chall: chall },
1053 success: (response) => {
1054 finishAddChallenge(response.id);
1060 // Callback function after a diagram was showed to accept
1061 // or refuse targetted challenge:
1062 decisionChallenge: function(accepted) {
1063 this.curChallToAccept.accepted = accepted;
1064 this.finishProcessingChallenge(this.curChallToAccept);
1065 document.getElementById("modalAccept").checked = false;
1067 finishProcessingChallenge: function(c) {
1070 sid: this.st.user.sid,
1071 id: this.st.user.id,
1072 name: this.st.user.name
1075 if (c.type == "live")
1076 // Remove all live challenges of both players
1077 this.send("deletechallenge_s", { data: { sids: [c.from.sid, c.seat.sid] } });
1079 // Corr challenge: just remove the challenge
1080 this.send("deletechallenge_s", { data: { cid: c.id } });
1082 const oppsid = this.getOppsid(c);
1084 this.send("refusechallenge", { data: c.id, target: oppsid });
1085 if (c.type == "corr") {
1089 { data: { id: c.id } }
1092 this.send("deletechallenge_s", { data: { cid: c.id } });
1095 // TODO: if several players click same challenge at the same time: problem
1096 clickChallenge: async function(c) {
1098 c.from.sid == this.st.user.sid || //live
1099 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1101 if (c.type == "corr" && this.st.user.id <= 0) {
1102 alert(this.st.tr["Please log in to accept corr challenges"]);
1106 const vModule = await import("@/variants/" + c.vname + ".js");
1107 window.V = vModule.VariantRules;
1109 // c.to == this.st.user.name (connected)
1111 const parsedFen = V.ParseFen(c.fen);
1112 c.mycolor = V.GetOppCol(parsedFen.turn);
1113 this.tchallDiag = getDiagram({
1114 position: parsedFen.position,
1115 orientation: c.mycolor
1118 this.curChallToAccept = c;
1119 document.getElementById("modalAccept").checked = true;
1121 else this.finishProcessingChallenge(c);
1125 if (c.type == "corr") {
1129 { data: { id: c.id } }
1132 this.send("deletechallenge_s", { data: { cid: c.id } });
1134 // In all cases, the challenge is consumed:
1135 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1137 // NOTE: when launching game, the challenge is already being deleted
1138 launchGame: function(c) {
1139 // White player index 0, black player index 1:
1142 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1143 : shuffle([c.from, c.seat]);
1144 // These game informations will be shared
1146 id: getRandString(),
1147 fen: c.fen || V.GenRandInitFen(c.randomness),
1148 randomness: c.randomness, //for rematch
1153 const notifyNewgame = () => {
1154 const oppsid = this.getOppsid(c);
1156 // Opponent is online
1157 this.send("startgame", { data: gameInfo, target: oppsid });
1158 // If new corr game, notify Hall (except opponent and me)
1159 if (c.type == "corr") {
1164 excluded: [this.st.user.sid, oppsid]
1168 // Notify MyGames page:
1173 targets: gameInfo.players
1176 // NOTE: no need to send the game to the room, since I'll connect
1177 // on game just after, the main Hall will be notified.
1179 if (c.type == "live") {
1181 this.startNewGame(gameInfo);
1183 // corr: game only on server
1188 // cid is useful to delete the challenge:
1193 success: (response) => {
1194 gameInfo.id = response.id;
1196 this.$router.push("/game/" + response.id);
1202 // NOTE: for live games only (corr games start on the server)
1203 startNewGame: function(gameInfo) {
1204 const game = Object.assign(
1208 // (other) Game infos: constant
1209 fenStart: gameInfo.fen,
1210 vname: this.getVname(gameInfo.vid),
1211 created: Date.now(),
1212 // Game state (including FEN): will be updated
1214 clocks: [-1, -1], //-1 = unstarted
1215 initime: [0, 0], //initialized later
1221 GameStorage.add(game, (err) => {
1222 // If an error occurred, game is not added: a tab already
1223 // added the game. Maybe a focused one, maybe not.
1224 // We know for sure that it emitted the gong start sound.
1225 // ==> Do not play it again.
1226 if (!err && this.st.settings.sound)
1227 new Audio("/sounds/newgame.flac").play().catch(() => {});
1228 this.$router.push("/game/" + gameInfo.id);
1231 document.hidden ? 500 + 1000 * Math.random() : 0
1238 <style lang="sass" scoped>
1246 #newgameDiv > .card, #acceptDiv > .card
1250 div#peopleWrap > .card
1253 @media screen and (min-width: 1281px)
1254 div#peopleWrap > .card
1257 @media screen and (max-width: 1280px)
1258 div#peopleWrap > .card
1261 @media screen and (max-width: 767px)
1262 div#peopleWrap > .card
1275 @media screen and (max-width: 767px)
1290 button.player-action
1294 background-color: #c5fefe !important
1297 background-color: #f9faee
1300 background-color: lightgreen
1302 background-color: red
1305 // margin-top set dynamically (depends if diagram showed or not)
1316 // width: 100% required for Firefox
1324 @media screen and (max-width: 767px)
1330 background-color: #FF5733
1332 background-color: #2B63B4
1334 background-color: #33B42B
1336 @media screen and (max-width: 767px)
1345 background-color: lightgrey