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"
189 v-show="gdisplay=='corr'"
190 :games="filterGames('corr')"
192 @show-game="showGame"
197 import { store } from "@/store";
198 import { checkChallenge } from "@/data/challengeCheck";
199 import { ArrayFun } from "@/utils/array";
200 import { ajax } from "@/utils/ajax";
201 import params from "@/parameters";
202 import { getRandString, shuffle } from "@/utils/alea";
203 import { getDiagram } from "@/utils/printDiagram";
204 import Chat from "@/components/Chat.vue";
205 import GameList from "@/components/GameList.vue";
206 import ChallengeList from "@/components/ChallengeList.vue";
207 import { GameStorage } from "@/utils/gameStorage";
208 import { processModalClick } from "@/utils/modalClick";
219 cdisplay: "live", //or corr
227 vid: parseInt(localStorage.getItem("vid")) || 0,
228 to: "", //name of challenged player (if any)
229 cadence: localStorage.getItem("cadence") || "",
230 randomness: parseInt(localStorage.getItem("randomness")) || 2,
231 // VariantRules object, stored to not interfere with
232 // diagrams of targetted challenges:
235 diag: "", //visualizing FEN
236 memorize: false //put settings in localStorage
239 curChallToAccept: {from: {}},
240 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
244 // Related to (killing of) self multi-connects:
250 // st.variants changes only once, at loading from [] to [...]
251 "st.variants": function() {
252 // Set potential challenges and games variant names:
253 this.challenges.concat(this.games).forEach(o => {
254 if (!o.vname) o.vname = this.getVname(o.vid);
256 if (!this.newchallenge.V && this.newchallenge.vid > 0)
257 this.loadNewchallVariant();
261 anonymousCount: function() {
263 Object.values(this.people).forEach(p => {
264 // Do not cound people who did not send their identity yet:
265 count += (!p.name && p.id === 0) ? 1 : 0;
270 created: function() {
271 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
272 this.loadNewchallVariant();
273 const my = this.st.user;
280 pages: [{ path: "/", focus: true }]
283 // Ask server for current corr games (all but mines)
288 data: { uid: this.st.user.id, excluded: true },
289 success: (response) => {
290 this.games = this.games.concat(
291 response.games.map(g => {
292 const type = this.classifyObject(g);
293 const vname = this.getVname(g.vid);
294 return Object.assign(
307 // Also ask for corr challenges (open + sent by/to me)
312 data: { uid: this.st.user.id },
313 success: (response) => {
314 // Gather all senders names, and then retrieve full identity:
315 // (TODO [perf]: some might be online...)
317 response.challenges.forEach(c => {
318 if (c.uid != this.st.user.id) names[c.uid] = "";
319 else if (!!c.target && c.target != this.st.user.id)
320 names[c.target] = "";
322 const addChallenges = () => {
323 names[this.st.user.id] = this.st.user.name; //in case of
324 this.challenges = this.challenges.concat(
325 response.challenges.map(c => {
326 const from = { name: names[c.uid], id: c.uid }; //or just name
327 const type = this.classifyObject(c);
328 const vname = this.getVname(c.vid);
329 return Object.assign(
335 to: c.target ? names[c.target] : ""
342 if (Object.keys(names).length > 0) {
347 data: { ids: Object.keys(names).join(",") },
348 success: (response2) => {
349 response2.users.forEach(u => {
350 names[u.id] = u.name;
356 } else addChallenges();
360 const connectAndPoll = () => {
361 this.send("connect");
362 this.send("pollclientsandgamers");
364 // Initialize connection
365 this.connexionString =
374 // Hall: path is "/" (could be hard-coded as well)
375 encodeURIComponent(this.$route.path);
376 this.conn = new WebSocket(this.connexionString);
377 this.conn.onopen = connectAndPoll;
378 this.conn.onmessage = this.socketMessageListener;
379 this.conn.onclose = this.socketCloseListener;
381 mounted: function() {
382 document.addEventListener('visibilitychange', this.visibilityChange);
383 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
384 let elt = document.getElementById(eltName);
385 elt.addEventListener("click", processModalClick);
387 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
388 b.addEventListener("click", () => {
389 this.newchallenge.cadence = b.innerHTML;
392 const dispCorr = this.$route.query["disp"];
394 dispCorr || localStorage.getItem("type-challenges") || "live";
396 dispCorr || localStorage.getItem("type-games") || "live";
397 this.setDisplay("c", showCtype);
398 this.setDisplay("g", showGtype);
400 beforeDestroy: function() {
401 document.removeEventListener('visibilitychange', this.visibilityChange);
402 this.send("disconnect");
405 getRandomnessClass: function(pc) {
407 ["random-" + pc.randomness]: true
410 visibilityChange: function() {
411 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
413 document.visibilityState == "visible"
418 partialResetNewchallenge: function() {
419 // Reset potential target and custom FEN:
420 this.newchallenge.to = "";
421 this.newchallenge.fen = "";
422 this.newchallenge.diag = "";
423 this.newchallenge.memorize = false;
425 showNewchallengeForm: function() {
426 this.partialResetNewchallenge();
427 window.doClick("modalNewgame");
429 addPresetChall: function(chall) {
430 // Add only if not already existing:
431 if (this.presetChalls.some(c =>
432 c.vid == chall.vid &&
433 c.cadence == chall.cadence &&
434 c.randomness == chall.randomness
438 const L = this.presetChalls.length;
439 this.presetChalls.push({
442 vname: chall.vname, //redundant, but easier
443 cadence: chall.cadence,
444 randomness: chall.randomness
446 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
448 removePresetChall: function(e, pchall) {
450 const pchallIdx = this.presetChalls.findIndex(pc => pc.index == pchall.index);
451 this.presetChalls.splice(pchallIdx, 1);
452 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
454 tchallButtonsMargin: function() {
455 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
458 cadenceFocusIfOpened: function() {
459 if (event.target.checked)
460 document.getElementById("cadence").focus();
462 send: function(code, obj) {
464 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
467 getVname: function(vid) {
468 const variant = this.st.variants.find(v => v.id == vid);
469 // this.st.variants might be uninitialized (variant == null)
470 return variant ? variant.name : "";
472 filterChallenges: function(type) {
473 return this.challenges.filter(c => c.type == type);
475 filterGames: function(type) {
476 return this.games.filter(g => g.type == type);
478 classifyObject: function(o) {
479 // o: challenge or game
480 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
482 setDisplay: function(letter, type, e) {
483 this[letter + "display"] = type;
484 localStorage.setItem(
485 "type-" + (letter == "c" ? "challenges" : "games"),
490 : document.getElementById("btn" + letter.toUpperCase() + type);
491 elt.classList.add("active");
492 elt.classList.remove("somethingnew"); //in case of
493 if (!!elt.previousElementSibling)
494 elt.previousElementSibling.classList.remove("active");
495 else elt.nextElementSibling.classList.remove("active");
497 isGamer: function(sid) {
498 return this.people[sid].pages
499 .some(p => p.focus && p.path.indexOf("/game/") >= 0);
501 isFocusedOnHall: function(sid) {
503 // This is meant to challenge people, thus the next 2 conditions:
504 this.st.user.id > 0 &&
505 sid != this.st.user.sid &&
506 this.people[sid].pages.some(p => p.path == "/" && p.focus)
509 challenge: function(sid) {
510 this.partialResetNewchallenge();
511 // Available, in Hall
512 this.newchallenge.to = this.people[sid].name;
513 // TODO: also store target sid to not re-search for it
514 document.getElementById("modalPeople").checked = false;
515 window.doClick("modalNewgame");
517 watchGame: function(sid) {
518 // In some game, maybe playing maybe not: show a random one
520 this.people[sid].pages.forEach(p => {
522 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
523 if (!!matchGid) gids.push(matchGid[0]);
526 const gid = gids[Math.floor(Math.random() * gids.length)];
527 const game = this.games.find(g => g.id == gid);
528 if (!!game) this.showGame(game);
529 else this.$router.push("/game/" + gid); //game vs. me
531 showGame: function(g) {
532 // NOTE: we are an observer, since only games I don't play are shown here
533 // ==> Moves sent by connected remote player(s) if live game
534 let url = "/game/" + g.id;
535 if (g.type == "live")
536 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
537 this.$router.push(url);
539 resetSocialColor: function() {
540 // TODO: this is called twice, once on opening an once on closing
541 document.getElementById("peopleBtn").classList.remove("somethingnew");
543 processChat: function(chat) {
544 this.send("newchat", { data: chat });
546 getOppsid: function(c) {
547 let oppsid = c.from.sid; //may not be defined if corr + offline opp
549 oppsid = Object.keys(this.people).find(
550 sid => this.people[sid].id == c.from.id
556 socketMessageListener: function(msg) {
557 if (!this.conn) return;
558 const data = JSON.parse(msg.data);
560 case "pollclientsandgamers": {
561 // Since people can be both in Hall and Game,
562 // need to track "askIdentity" requests:
563 let identityAsked = {};
564 data.sockIds.forEach(s => {
565 const page = s.page || "/";
566 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
567 this.send("askidentity", { target: s.sid, page: page });
568 identityAsked[s.sid] = true;
570 if (!this.people[s.sid]) {
571 // Do not set name or id: identity unknown yet
572 this.people[s.sid] = { pages: [{path: page, focus: true}] };
574 else if (!(this.people[s.sid].pages.find(p => p.path == page)))
575 this.people[s.sid].pages.push({ path: page, focus: true });
578 this.send("askchallenges", { target: s.sid });
580 else this.send("askgame", { target: s.sid, page: page });
586 const page = data.page || "/";
587 // Only ask game / challenges if first connexion:
588 if (!this.people[data.from]) {
589 this.people[data.from] = { pages: [{ path: page, focus: true }] };
590 if (data.code == "connect")
591 this.send("askchallenges", { target: data.from });
592 else this.send("askgame", { target: data.from, page: page });
594 // Append page if not already in list
595 if (!(this.people[data.from].pages.find(p => p.path == page)))
596 this.people[data.from].pages.push({ path: page, focus: true });
598 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
599 // Identity not known yet
600 this.newConnect[data.from] = true; //for self multi-connects tests
601 this.send("askidentity", { target: data.from, page: page });
606 case "gdisconnect": {
607 // If the user reloads the page twice very quickly (experienced with Firefox),
608 // the first reload won't have time to connect but will trigger a "close" event anyway.
609 // ==> Next check is required.
610 if (!this.people[data.from]) return;
611 // Disconnect means no more tmpIds:
612 if (data.code == "disconnect") {
613 // Remove the live challenges sent by this player:
616 c => c.type == "live" && c.from.sid == data.from,
620 // Remove the matching live game if now unreachable
621 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
622 const gidx = this.games.findIndex(g => g.id == gid);
624 const game = this.games[gidx];
626 game.type == "live" &&
627 game.rids.length == 1 &&
628 game.rids[0] == data.from
630 this.games.splice(gidx, 1);
634 const page = data.page || "/";
635 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
636 if (this.people[data.from].pages.length == 0)
637 this.$delete(this.people, data.from);
641 // If user reload a page, focus may arrive earlier than connect
642 if (!!this.people[data.from]) {
643 this.people[data.from].pages
644 .find(p => p.path == data.page).focus = true;
645 this.$forceUpdate(); //TODO: shouldn't be required
649 if (!!this.people[data.from]) {
650 this.people[data.from].pages
651 .find(p => p.path == data.page).focus = false;
652 this.$forceUpdate(); //TODO: shouldn't be required
656 // I logged in elsewhere:
658 alert(this.st.tr["New connexion detected: tab now offline"]);
660 case "askidentity": {
661 // Request for identification (TODO: anonymous shouldn't need to reply)
663 // Decompose to avoid revealing email
664 name: this.st.user.name,
665 sid: this.st.user.sid,
668 this.send("identity", { data: me, target: data.from });
672 const user = data.data;
673 let player = this.people[user.sid];
674 // player.pages is already set
676 player.name = user.name;
677 // TODO: this.$set(people, ...) fails. So forceUpdate.
678 // But this shouldn't be like that!
680 // If I multi-connect, kill current connexion if no mark (I'm older)
681 if (this.newConnect[user.sid]) {
684 user.id == this.st.user.id &&
685 user.sid != this.st.user.sid &&
686 !this.killed[this.st.user.sid]
688 this.send("killme", { sid: this.st.user.sid });
689 this.killed[this.st.user.sid] = true;
691 delete this.newConnect[user.sid];
695 case "askchallenges": {
696 // Send my current live challenges (if any)
697 const myChallenges = this.challenges
699 c.from.sid == this.st.user.sid && c.type == "live"
702 // NOTE: in principle, should only send targeted challenge to the target.
703 // But we may not know yet the identity of the target (just name),
704 // so cannot decide if data.from is the target or not.
707 from: this.st.user.sid,
709 randomness: c.randomness,
716 if (myChallenges.length > 0)
717 this.send("challenges", { data: myChallenges, target: data.from });
720 case "challenges": //after "askchallenges"
721 data.data.forEach(this.addChallenge);
724 this.addChallenge(data.data);
726 case "refusechallenge": {
727 const cid = data.data;
728 ArrayFun.remove(this.challenges, c => c.id == cid);
729 alert(this.st.tr["Challenge declined"]);
732 case "deletechallenge_s": {
733 // NOTE: the challenge(s) may be already removed
734 const cref = data.data;
735 if (!!cref.cid) ArrayFun.remove(this.challenges, c => c.id == cref.cid);
736 else if (!!cref.sids) {
737 cref.sids.forEach(s => {
740 c => c.type == "live" && c.from.sid == s,
747 case "game": //individual request
749 const game = data.data;
750 // Ignore games where I play (will go in MyGames page)
751 if (game.players.every(p =>
752 p.sid != this.st.user.sid || p.uid != this.st.user.id))
754 let locGame = this.games.find(g => g.id == game.id);
757 newGame.type = this.classifyObject(game);
758 newGame.vname = this.getVname(game.vid);
760 // New game from Hall
762 newGame.rids = [game.rid];
763 delete newGame["rid"];
764 this.games.push(newGame);
766 (newGame.type == "live" && this.gdisplay == "corr") ||
767 (newGame.type == "corr" && this.gdisplay == "live")
770 .getElementById("btnG" + newGame.type)
771 .classList.add("somethingnew");
774 // Append rid (if not already in list)
775 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
781 let g = this.games.find(g => g.id == data.gid);
782 if (!!g) g.score = data.score;
786 // New game just started, I'm involved
787 const gameInfo = data.data;
788 if (this.classifyObject(gameInfo) == "live")
789 this.startNewGame(gameInfo);
792 this.st.tr["New correspondance game:"] +
793 " <a href='#/game/" +
799 document.getElementById("modalInfo").checked = true;
804 this.newChat = data.data;
805 if (!document.getElementById("modalPeople").checked)
806 document.getElementById("peopleBtn").classList.add("somethingnew");
810 socketCloseListener: function() {
811 if (!this.conn) return;
812 this.conn = new WebSocket(this.connexionString);
813 this.conn.addEventListener("message", this.socketMessageListener);
814 this.conn.addEventListener("close", this.socketCloseListener);
816 // Challenge lifecycle:
817 addChallenge: function(chall) {
818 // NOTE about next condition: see "askchallenges" case.
821 (this.people[chall.from].id > 0 &&
822 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
824 let newChall = Object.assign({}, chall);
825 newChall.type = this.classifyObject(chall);
826 newChall.randomness = chall.randomness;
827 newChall.added = Date.now();
828 let fromValues = Object.assign({}, this.people[chall.from]);
829 delete fromValues["pages"]; //irrelevant in this context
830 newChall.from = Object.assign({ sid: chall.from }, fromValues);
831 newChall.vname = this.getVname(newChall.vid);
832 this.challenges.push(newChall);
834 (newChall.type == "live" && this.cdisplay == "corr") ||
835 (newChall.type == "corr" && this.cdisplay == "live")
838 .getElementById("btnC" + newChall.type)
839 .classList.add("somethingnew");
843 loadNewchallVariant: async function(cb) {
844 const vname = this.getVname(this.newchallenge.vid);
845 const vModule = await import("@/variants/" + vname + ".js");
846 this.newchallenge.V = vModule.VariantRules;
847 this.newchallenge.vname = vname;
851 trySetNewchallDiag: function() {
852 if (!this.newchallenge.fen) {
853 this.newchallenge.diag = "";
856 // If vid > 0 then the variant is loaded (function above):
857 window.V = this.newchallenge.V;
859 this.newchallenge.vid > 0 &&
860 !!this.newchallenge.fen &&
861 V.IsGoodFen(this.newchallenge.fen)
863 const parsedFen = V.ParseFen(this.newchallenge.fen);
864 this.newchallenge.diag = getDiagram({
865 position: parsedFen.position,
866 orientation: parsedFen.turn
870 newChallFromPreset(pchall) {
871 this.partialResetNewchallenge();
872 this.newchallenge.vid = pchall.vid;
873 this.newchallenge.cadence = pchall.cadence;
874 this.newchallenge.randomness = pchall.randomness;
875 this.issueNewChallenge();
877 issueNewChallenge: async function() {
878 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
879 this.newchallenge.cadence += "+0"; //assume minutes, no increment
880 const ctype = this.classifyObject(this.newchallenge);
881 // TODO: cadence still unchecked so ctype could be wrong...
883 if (!this.newchallenge.vid)
884 error = this.st.tr["Please select a variant"];
885 else if (ctype == "corr" && this.st.user.id <= 0)
886 error = this.st.tr["Please log in to play correspondance games"];
887 else if (!!this.newchallenge.to) {
888 if (this.newchallenge.to == this.st.user.name)
889 error = this.st.tr["Self-challenge is forbidden"];
892 Object.values(this.people).every(p => p.name != this.newchallenge.to)
894 error = this.newchallenge.to + " " + this.st.tr["is not online"];
900 window.V = this.newchallenge.V;
901 error = checkChallenge(this.newchallenge);
906 // NOTE: "from" information is not required here
907 let chall = Object.assign({}, this.newchallenge);
908 // Add only if not already issued (not counting target or FEN):
909 if (this.challenges.some(c =>
910 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
911 c.vid == chall.vid &&
912 c.cadence == chall.cadence &&
913 c.randomness == chall.randomness
915 alert(this.st.tr["Challenge already exists"]);
918 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
920 delete chall["diag"];
921 const finishAddChallenge = cid => {
922 chall.id = cid || "c" + getRandString();
923 const MAX_ALLOWED_CHALLS = 3;
924 // Remove oldest challenge if 3 found: only 3 at a time of a given type
925 let countMyChalls = 0;
926 let challToDelIdx = 0;
927 let oldestAdded = Number.MAX_SAFE_INTEGER;
928 for (let i=0; i<this.challenges.length; i++) {
929 const c = this.challenges[i];
932 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
935 if (c.added < oldestAdded) {
937 oldestAdded = c.added;
941 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
944 { data: { cid: this.challenges[challToDelIdx].id } }
946 if (ctype == "corr") {
950 { data: { id: this.challenges[challToDelIdx].id } }
953 this.challenges.splice(challToDelIdx, 1);
955 this.send("newchallenge", {
956 data: Object.assign({ from: this.st.user.sid }, chall)
958 // Add new challenge:
960 // Decompose to avoid revealing email
961 sid: this.st.user.sid,
963 name: this.st.user.name
965 chall.added = Date.now();
966 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
968 chall.vname = this.newchallenge.vname;
969 this.challenges.push(chall);
970 // Remember cadence + vid for quicker further challenges:
971 localStorage.setItem("cadence", chall.cadence);
972 localStorage.setItem("vid", chall.vid);
973 localStorage.setItem("randomness", chall.randomness);
974 document.getElementById("modalNewgame").checked = false;
975 // Show the challenge if not on current display
977 (ctype == "live" && this.cdisplay == "corr") ||
978 (ctype == "corr" && this.cdisplay == "live")
980 this.setDisplay('c', ctype);
983 if (ctype == "live") {
984 // Live challenges have a random ID
985 finishAddChallenge(null);
987 // Correspondance game: send challenge to server
992 data: { chall: chall },
993 success: (response) => {
994 finishAddChallenge(response.cid);
1000 // Callback function after a diagram was showed to accept
1001 // or refuse targetted challenge:
1002 decisionChallenge: function(accepted) {
1003 this.curChallToAccept.accepted = accepted;
1004 this.finishProcessingChallenge(this.curChallToAccept);
1005 document.getElementById("modalAccept").checked = false;
1007 finishProcessingChallenge: function(c) {
1010 // Again, avoid c.seat = st.user to not reveal email
1011 sid: this.st.user.sid,
1012 id: this.st.user.id,
1013 name: this.st.user.name
1016 if (c.type == "live")
1017 // Remove all live challenges of both players
1018 this.send("deletechallenge_s", { data: { sids: [c.from.sid, c.seat.sid] } });
1020 // Corr challenge: just remove the challenge
1021 this.send("deletechallenge_s", { data: { cid: c.id } });
1023 const oppsid = this.getOppsid(c);
1025 this.send("refusechallenge", { data: c.id, target: oppsid });
1026 if (c.type == "corr") {
1030 { data: { id: c.id } }
1033 this.send("deletechallenge_s", { data: { cid: c.id } });
1036 // TODO: if several players click same challenge at the same time: problem
1037 clickChallenge: async function(c) {
1039 c.from.sid == this.st.user.sid || //live
1040 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1042 if (c.type == "corr" && this.st.user.id <= 0) {
1043 alert(this.st.tr["Please log in to accept corr challenges"]);
1047 const vModule = await import("@/variants/" + c.vname + ".js");
1048 window.V = vModule.VariantRules;
1050 // c.to == this.st.user.name (connected)
1052 const parsedFen = V.ParseFen(c.fen);
1053 c.mycolor = V.GetOppCol(parsedFen.turn);
1054 this.tchallDiag = getDiagram({
1055 position: parsedFen.position,
1056 orientation: c.mycolor
1059 this.curChallToAccept = c;
1060 document.getElementById("modalAccept").checked = true;
1062 else this.finishProcessingChallenge(c);
1066 if (c.type == "corr") {
1070 { data: { id: c.id } }
1073 this.send("deletechallenge_s", { data: { cid: c.id } });
1075 // In all cases, the challenge is consumed:
1076 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1078 // NOTE: when launching game, the challenge is already being deleted
1079 launchGame: function(c) {
1082 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1083 : shuffle([c.from, c.seat]);
1084 // Convention for players IDs in stored games is 'uid'
1085 players.forEach(p => {
1087 pWithUid["uid"] = p.id;
1088 delete pWithUid["id"];
1090 // These game informations will be shared
1092 id: getRandString(),
1093 fen: c.fen || V.GenRandInitFen(c.randomness),
1094 // White player index 0, black player index 1:
1096 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1097 : shuffle([c.from, c.seat]),
1101 const notifyNewgame = () => {
1102 const oppsid = this.getOppsid(c);
1104 // Opponent is online
1105 this.send("startgame", { data: gameInfo, target: oppsid });
1106 // Send game info (only if live) to everyone except me and opponent
1107 // TODO: this double message send could be avoided.
1108 this.send("newgame", { data: gameInfo, oppsid: oppsid });
1109 // Also to MyGames page:
1114 targets: gameInfo.players.map(p => {
1115 return { sid: p.sid, uid: p.uid };
1120 if (c.type == "live") {
1122 this.startNewGame(gameInfo);
1124 // corr: game only on server
1129 // cid is useful to delete the challenge:
1130 data: { gameInfo: gameInfo, cid: c.id },
1131 success: (response) => {
1132 gameInfo.id = response.gameId;
1134 this.$router.push("/game/" + response.gameId);
1140 // NOTE: for live games only (corr games start on the server)
1141 startNewGame: function(gameInfo) {
1142 const game = Object.assign(
1146 // (other) Game infos: constant
1147 fenStart: gameInfo.fen,
1148 vname: this.getVname(gameInfo.vid),
1149 created: Date.now(),
1150 // Game state (including FEN): will be updated
1152 clocks: [-1, -1], //-1 = unstarted
1153 initime: [0, 0], //initialized later
1159 GameStorage.add(game, (err) => {
1160 // If an error occurred, game is not added: a tab already
1161 // added the game and (if focused) is redirected toward it.
1162 // If no error and the tab is hidden: do not show anything.
1163 if (!err && !document.hidden) {
1164 if (this.st.settings.sound)
1165 new Audio("/sounds/newgame.flac").play().catch(() => {});
1166 this.$router.push("/game/" + gameInfo.id);
1170 document.hidden ? 500 + 1000 * Math.random() : 0
1177 <style lang="sass" scoped>
1185 #newgameDiv > .card, #acceptDiv > .card
1189 div#peopleWrap > .card
1192 @media screen and (min-width: 1281px)
1193 div#peopleWrap > .card
1196 @media screen and (max-width: 1280px)
1197 div#peopleWrap > .card
1200 @media screen and (max-width: 767px)
1201 div#peopleWrap > .card
1214 @media screen and (max-width: 767px)
1229 button.player-action
1233 background-color: #c5fefe !important
1236 background-color: #f9faee
1239 background-color: lightgreen
1241 background-color: red
1244 // margin-top set dynamically (depends if diagram showed or not)
1255 // width: 100% required for Firefox
1263 @media screen and (max-width: 767px)
1269 background-color: #FF5733
1271 background-color: #2B63B4
1273 background-color: #33B42B
1275 @media screen and (max-width: 767px)
1280 background-color: lightgrey