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 { ArrayFun } from "@/utils/array";
209 import { ajax } from "@/utils/ajax";
210 import params from "@/parameters";
211 import { getRandString, shuffle } from "@/utils/alea";
212 import { getDiagram } from "@/utils/printDiagram";
213 import Chat from "@/components/Chat.vue";
214 import GameList from "@/components/GameList.vue";
215 import ChallengeList from "@/components/ChallengeList.vue";
216 import { GameStorage } from "@/utils/gameStorage";
217 import { processModalClick } from "@/utils/modalClick";
228 cdisplay: "live", //or corr
230 // timestamp of last showed (oldest) corr game:
231 cursor: Number.MAX_SAFE_INTEGER,
232 // hasMore == TRUE: a priori there could be more games to load
240 vid: parseInt(localStorage.getItem("vid")) || 0,
241 to: "", //name of challenged player (if any)
242 cadence: localStorage.getItem("cadence") || "",
243 randomness: parseInt(localStorage.getItem("challRandomness")) || 2,
244 // VariantRules object, stored to not interfere with
245 // diagrams of targetted challenges:
248 diag: "", //visualizing FEN
249 memorize: false //put settings in localStorage
252 curChallToAccept: {from: {}},
253 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
256 // Related to (killing of) self multi-connects:
262 // st.variants changes only once, at loading from [] to [...]
263 "st.variants": function() {
264 // Set potential challenges and games variant names:
265 this.challenges.concat(this.games).forEach(o => {
266 if (!o.vname) o.vname = this.getVname(o.vid);
268 if (!this.newchallenge.V && this.newchallenge.vid > 0)
269 this.loadNewchallVariant();
272 created: function() {
273 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
274 this.loadNewchallVariant();
275 const my = this.st.user;
282 pages: [{ path: "/", focus: true }]
285 const connectAndPoll = () => {
286 this.send("connect");
287 this.send("pollclientsandgamers");
289 // Initialize connection
290 this.connexionString =
299 // Hall: path is "/" (could be hard-coded as well)
300 encodeURIComponent(this.$route.path);
301 this.conn = new WebSocket(this.connexionString);
302 this.conn.onopen = connectAndPoll;
303 this.conn.addEventListener("message", this.socketMessageListener);
304 this.conn.addEventListener("close", this.socketCloseListener);
306 mounted: function() {
307 document.addEventListener('visibilitychange', this.visibilityChange);
308 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
309 document.getElementById(eltName)
310 .addEventListener("click", processModalClick);
312 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
313 b.addEventListener("click", () => {
314 this.newchallenge.cadence = b.innerHTML;
317 const dispCorr = this.$route.query["disp"];
319 dispCorr || localStorage.getItem("type-challenges") || "live";
321 dispCorr || localStorage.getItem("type-games") || "live";
322 this.setDisplay('c', showCtype);
323 this.setDisplay('g', showGtype);
324 // Ask server for current corr games (all but mines)
326 // Also ask for corr challenges (open + sent by/to me)
327 // List them all, because they are not supposed to be that many (TODO?)
332 data: { uid: this.st.user.id },
333 success: (response) => {
335 response.challenges.length > 0 &&
336 this.challenges.length == 0 &&
337 this.cdisplay == "live"
340 .getElementById("btnCcorr")
341 .classList.add("somethingnew");
343 // Gather all senders names, and then retrieve full identity:
344 // (TODO [perf]: some might be online...)
346 response.challenges.forEach(c => {
347 if (c.uid != this.st.user.id) names[c.uid] = "";
348 else if (!!c.target && c.target != this.st.user.id)
349 names[c.target] = "";
351 const addChallenges = () => {
352 names[this.st.user.id] = this.st.user.name; //in case of
353 this.challenges = this.challenges.concat(
354 response.challenges.map(c => {
355 const from = { name: names[c.uid], id: c.uid }; //or just name
356 const type = this.classifyObject(c);
357 const vname = this.getVname(c.vid);
358 return Object.assign(
364 to: c.target ? names[c.target] : ""
371 if (Object.keys(names).length > 0) {
376 data: { ids: Object.keys(names).join(",") },
377 success: (response2) => {
378 response2.users.forEach(u => {
379 names[u.id] = u.name;
385 } else addChallenges();
390 beforeDestroy: function() {
391 document.removeEventListener('visibilitychange', this.visibilityChange);
392 this.send("disconnect");
395 getRandomnessClass: function(pc) {
397 ["random-" + pc.randomness]: true
400 openModalPeople: function() {
401 window.doClick("modalPeople");
402 document.getElementById("inputChat").focus();
404 anonymousCount: function() {
406 Object.values(this.people).forEach(p => {
407 // Do not cound people who did not send their identity yet:
408 count += (!p.name && p.id === 0) ? 1 : 0;
412 visibilityChange: function() {
413 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
415 document.visibilityState == "visible"
420 partialResetNewchallenge: function() {
421 // Reset potential target and custom FEN:
422 this.newchallenge.to = "";
423 this.newchallenge.fen = "";
424 this.newchallenge.diag = "";
425 this.newchallenge.memorize = false;
427 showNewchallengeForm: function() {
428 this.partialResetNewchallenge();
429 window.doClick("modalNewgame");
431 addPresetChall: function(chall) {
432 // Add only if not already existing:
433 if (this.presetChalls.some(c =>
434 c.vid == chall.vid &&
435 c.cadence == chall.cadence &&
436 c.randomness == chall.randomness
440 const L = this.presetChalls.length;
441 this.presetChalls.push({
444 vname: chall.vname, //redundant, but easier
445 cadence: chall.cadence,
446 randomness: chall.randomness
448 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
450 removePresetChall: function(e, pchall) {
452 const pchallIdx = this.presetChalls.findIndex(pc => pc.index == pchall.index);
453 this.presetChalls.splice(pchallIdx, 1);
454 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
456 tchallButtonsMargin: function() {
457 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
460 changeChallTarget: function() {
461 if (!this.newchallenge.to) {
462 // Reset potential FEN + diagram
463 this.newchallenge.fen = "";
464 this.newchallenge.diag = "";
467 cadenceFocusIfOpened: function() {
468 if (event.target.checked)
469 document.getElementById("cadence").focus();
471 send: function(code, obj) {
473 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
476 getVname: function(vid) {
477 const variant = this.st.variants.find(v => v.id == vid);
478 // this.st.variants might be uninitialized (variant == null)
479 return variant ? variant.name : "";
481 filterChallenges: function(type) {
482 return this.challenges.filter(c => c.type == type);
484 filterGames: function(type) {
485 return this.games.filter(g => g.type == type);
487 classifyObject: function(o) {
488 // o: challenge or game
489 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
491 setDisplay: function(letter, type, e) {
492 this[letter + "display"] = type;
493 localStorage.setItem(
494 "type-" + (letter == "c" ? "challenges" : "games"),
499 : document.getElementById("btn" + letter.toUpperCase() + type);
500 elt.classList.add("active");
501 elt.classList.remove("somethingnew"); //in case of
502 if (!!elt.previousElementSibling)
503 elt.previousElementSibling.classList.remove("active");
504 else elt.nextElementSibling.classList.remove("active");
506 isGamer: function(sid) {
507 return this.people[sid].pages
508 .some(p => p.focus && p.path.indexOf("/game/") >= 0);
510 isFocusedOnHall: function(sid) {
512 // This is meant to challenge people, thus the next 2 conditions:
513 this.st.user.id > 0 &&
514 sid != this.st.user.sid &&
515 this.people[sid].pages.some(p => p.path == "/" && p.focus)
518 challenge: function(sid) {
519 this.partialResetNewchallenge();
520 // Available, in Hall
521 this.newchallenge.to = this.people[sid].name;
522 // TODO: also store target sid to not re-search for it
523 document.getElementById("modalPeople").checked = false;
524 window.doClick("modalNewgame");
526 watchGame: function(sid) {
527 // In some game, maybe playing maybe not: show a random one
529 this.people[sid].pages.forEach(p => {
531 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
532 if (!!matchGid) gids.push(matchGid[0]);
535 const gid = gids[Math.floor(Math.random() * gids.length)];
536 const game = this.games.find(g => g.id == gid);
537 if (!!game) this.showGame(game);
538 else this.$router.push("/game/" + gid); //game vs. me
540 showGame: function(g) {
541 // NOTE: we are an observer, since only games I don't play are shown here
542 // ==> Moves sent by connected remote player(s) if live game
543 this.$router.push("/game/" + g.id);
545 resetSocialColor: function() {
546 // TODO: this is called twice, once on opening an once on closing
547 document.getElementById("peopleBtn").classList.remove("somethingnew");
549 processChat: function(chat) {
550 this.send("newchat", { data: chat });
552 getOppsid: function(c) {
553 let oppsid = c.from.sid; //may not be defined if corr + offline opp
555 oppsid = Object.keys(this.people).find(
556 sid => this.people[sid].id == c.from.id
562 socketMessageListener: function(msg) {
563 if (!this.conn) return;
564 const data = JSON.parse(msg.data);
566 case "pollclientsandgamers": {
567 // Since people can be both in Hall and Game,
568 // need to track "askIdentity" requests:
569 let identityAsked = {};
570 // TODO: shuffling and random filtering on server, if
571 // the room is really crowded.
572 data.sockIds.forEach(s => {
573 const page = s.page || "/";
574 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
575 this.send("askidentity", { target: s.sid, page: page });
576 identityAsked[s.sid] = true;
578 if (!this.people[s.sid]) {
579 // Do not set name or id: identity unknown yet
580 this.people[s.sid] = { pages: [{path: page, focus: true}] };
582 else if (!(this.people[s.sid].pages.find(p => p.path == page)))
583 this.people[s.sid].pages.push({ path: page, focus: true });
586 this.send("askchallenges", { target: s.sid });
587 // Peer is in Game: ask only if live game
588 else if (!page.match(/\/[0-9]+$/))
589 this.send("askgame", { target: s.sid, page: page });
595 const page = data.page || "/";
596 if (data.code == "connect") {
597 // Ask challenges only on first connexion:
598 if (!this.people[data.from])
599 this.send("askchallenges", { target: data.from });
601 // Ask game only if live:
602 else if (!page.match(/\/[0-9]+$/))
603 this.send("askgame", { target: data.from, page: page });
604 if (!this.people[data.from])
605 this.people[data.from] = { pages: [{ path: page, focus: true }] };
607 // Append page if not already in list
608 if (!(this.people[data.from].pages.find(p => p.path == page)))
609 this.people[data.from].pages.push({ path: page, focus: true });
611 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
612 // Identity not known yet
613 this.newConnect[data.from] = true; //for self multi-connects tests
614 this.send("askidentity", { target: data.from, page: page });
619 case "gdisconnect": {
620 // If the user reloads the page twice very quickly (experienced with Firefox),
621 // the first reload won't have time to connect but will trigger a "close" event anyway.
622 // ==> Next check is required.
623 if (!this.people[data.from]) return;
624 const page = data.page || "/";
625 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
626 if (this.people[data.from].pages.length == 0)
627 this.$delete(this.people, data.from);
628 // Disconnect means no more tmpIds:
629 if (data.code == "disconnect") {
630 // Remove the live challenges sent by this player:
633 c => c.type == "live" && c.from.sid == data.from,
637 // Remove the matching live game if now unreachable
638 const gid = page.match(/[a-zA-Z0-9]+$/)[0];
639 // Corr games are always reachable:
640 if (!gid.match(/^[0-9]+$/)) {
641 // Live games are reachable as long as someone is on the game page
642 if (Object.values(this.people).every(p =>
643 p.pages.every(pg => pg.path != page))) {
644 ArrayFun.remove(this.games, g => g.id == gid);
651 // If user reload a page, focus may arrive earlier than connect
652 if (!!this.people[data.from]) {
653 this.people[data.from].pages
654 .find(p => p.path == data.page).focus = true;
655 this.$forceUpdate(); //TODO: shouldn't be required
659 if (!!this.people[data.from]) {
660 this.people[data.from].pages
661 .find(p => p.path == data.page).focus = false;
662 this.$forceUpdate(); //TODO: shouldn't be required
666 // I logged in elsewhere:
667 this.conn.removeEventListener("message", this.socketMessageListener);
668 this.conn.removeEventListener("close", this.socketCloseListener);
670 alert(this.st.tr["New connexion detected: tab now offline"]);
672 case "askidentity": {
673 // Request for identification
675 // Decompose to avoid revealing email
676 name: this.st.user.name,
677 sid: this.st.user.sid,
680 this.send("identity", { data: me, target: data.from });
684 const user = data.data;
685 let player = this.people[user.sid];
686 // player.pages is already set
688 player.name = user.name;
689 // TODO: this.$set(people, ...) fails. So forceUpdate.
690 // But this shouldn't be like that!
692 // If I multi-connect, kill current connexion if no mark (I'm older)
693 if (this.newConnect[user.sid]) {
696 user.id == this.st.user.id &&
697 user.sid != this.st.user.sid &&
698 !this.killed[this.st.user.sid]
700 this.send("killme", { sid: this.st.user.sid });
701 this.killed[this.st.user.sid] = true;
703 delete this.newConnect[user.sid];
707 case "askchallenges": {
708 // Send my current live challenges (if any)
709 const myChallenges = this.challenges
711 c.from.sid == this.st.user.sid && c.type == "live"
714 // NOTE: in principle, should only send targeted challenge to the target.
715 // But we may not know yet the identity of the target (just name),
716 // so cannot decide if data.from is the target or not.
719 from: this.st.user.sid,
721 randomness: c.randomness,
728 if (myChallenges.length > 0)
729 this.send("challenges", { data: myChallenges, target: data.from });
732 case "challenges": //after "askchallenges"
733 data.data.forEach(this.addChallenge);
736 this.addChallenge(data.data);
738 case "refusechallenge": {
739 const cid = data.data;
740 ArrayFun.remove(this.challenges, c => c.id == cid);
741 alert(this.st.tr["Challenge declined"]);
744 case "deletechallenge_s": {
745 // NOTE: the challenge(s) may be already removed
746 const cref = data.data;
747 if (!!cref.cid) ArrayFun.remove(this.challenges, c => c.id == cref.cid);
748 else if (!!cref.sids) {
749 cref.sids.forEach(s => {
752 c => c.type == "live" && c.from.sid == s,
759 case "game": // Individual request
761 const game = data.data;
762 // Ignore games where I play (will go in MyGames page),
763 // and also games that I already received.
765 game.players.every(p =>
766 p.sid != this.st.user.sid && p.id != this.st.user.id) &&
767 this.games.findIndex(g => g.id == game.id) == -1
770 newGame.type = this.classifyObject(game);
771 newGame.vname = this.getVname(game.vid);
773 // New game from Hall
775 this.games.push(newGame);
777 (newGame.type == "live" && this.gdisplay == "corr") ||
778 (newGame.type == "corr" && this.gdisplay == "live")
781 .getElementById("btnG" + newGame.type)
782 .classList.add("somethingnew");
788 let g = this.games.find(g => g.id == data.gid);
789 if (!!g) g.score = data.score;
793 // New game just started, I'm involved
794 const gameInfo = data.data;
795 if (this.classifyObject(gameInfo) == "live")
796 this.startNewGame(gameInfo);
799 this.st.tr["New correspondance game:"] +
800 " <a href='#/game/" +
806 document.getElementById("modalInfo").checked = true;
811 this.$refs["chatcomp"].newChat(data.data);
812 if (!document.getElementById("modalPeople").checked)
813 document.getElementById("peopleBtn").classList.add("somethingnew");
817 socketCloseListener: function() {
818 if (!this.conn) return;
819 this.conn = new WebSocket(this.connexionString);
820 this.conn.addEventListener("message", this.socketMessageListener);
821 this.conn.addEventListener("close", this.socketCloseListener);
823 loadMoreCorr: function() {
829 uid: this.st.user.id,
833 const L = res.games.length;
836 this.cursor == Number.MAX_SAFE_INTEGER &&
837 this.games.length == 0 &&
838 this.gdisplay == "live"
840 // First loading: show indicators
842 .getElementById("btnGcorr")
843 .classList.add("somethingnew");
845 this.cursor = res.games[L - 1].created;
846 let moreGames = res.games.map(g => {
847 const vname = this.getVname(g.vid);
848 return Object.assign(
857 this.games = this.games.concat(moreGames);
858 } else this.hasMore = false;
863 // Challenge lifecycle:
864 addChallenge: function(chall) {
865 // NOTE about next condition: see "askchallenges" case.
868 (this.people[chall.from].id > 0 &&
869 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
871 let newChall = Object.assign({}, chall);
872 newChall.type = this.classifyObject(chall);
873 newChall.randomness = chall.randomness;
874 newChall.added = Date.now();
875 let fromValues = Object.assign({}, this.people[chall.from]);
876 delete fromValues["pages"]; //irrelevant in this context
877 newChall.from = Object.assign({ sid: chall.from }, fromValues);
878 newChall.vname = this.getVname(newChall.vid);
879 this.challenges.push(newChall);
881 (newChall.type == "live" && this.cdisplay == "corr") ||
882 (newChall.type == "corr" && this.cdisplay == "live")
885 .getElementById("btnC" + newChall.type)
886 .classList.add("somethingnew");
890 loadNewchallVariant: async function(cb) {
891 const vname = this.getVname(this.newchallenge.vid);
892 await import("@/variants/" + vname + ".js")
894 window.V = vModule[vname + "Rules"];
895 this.newchallenge.V = window.V;
896 this.newchallenge.vname = vname;
900 trySetNewchallDiag: function() {
901 if (!this.newchallenge.fen) {
902 this.newchallenge.diag = "";
905 // If vid > 0 then the variant is loaded (function above):
906 window.V = this.newchallenge.V;
908 this.newchallenge.vid > 0 &&
909 !!this.newchallenge.fen &&
910 V.IsGoodFen(this.newchallenge.fen)
912 const parsedFen = V.ParseFen(this.newchallenge.fen);
913 this.newchallenge.diag = getDiagram({
914 position: parsedFen.position,
915 orientation: parsedFen.turn
917 } else this.newchallenge.diag = "";
919 newChallFromPreset(pchall) {
920 this.partialResetNewchallenge();
921 this.newchallenge.vid = pchall.vid;
922 this.newchallenge.cadence = pchall.cadence;
923 this.newchallenge.randomness = pchall.randomness;
924 this.loadNewchallVariant(this.issueNewChallenge);
926 issueNewChallenge: async function() {
927 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
928 this.newchallenge.cadence += "+0"; //assume minutes, no increment
929 const ctype = this.classifyObject(this.newchallenge);
930 // TODO: cadence still unchecked so ctype could be wrong...
932 if (!this.newchallenge.vid)
933 error = this.st.tr["Please select a variant"];
934 else if (ctype == "corr" && this.st.user.id <= 0)
935 error = this.st.tr["Please log in to play correspondance games"];
936 else if (!!this.newchallenge.to) {
937 if (this.newchallenge.to == this.st.user.name)
938 error = this.st.tr["Self-challenge is forbidden"];
941 Object.values(this.people).every(p => p.name != this.newchallenge.to)
943 error = this.newchallenge.to + " " + this.st.tr["is not online"];
950 window.V = this.newchallenge.V;
951 error = checkChallenge(this.newchallenge);
956 // NOTE: "from" information is not required here
957 let chall = Object.assign({}, this.newchallenge);
958 // Add only if not already issued (not counting target or FEN):
959 if (this.challenges.some(c =>
960 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
961 c.vid == chall.vid &&
962 c.cadence == chall.cadence &&
963 c.randomness == chall.randomness
965 alert(this.st.tr["Challenge already exists"]);
968 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
970 delete chall["diag"];
971 const finishAddChallenge = cid => {
972 chall.id = cid || "c" + getRandString();
973 const MAX_ALLOWED_CHALLS = 3;
974 // Remove oldest challenge if 3 found: only 3 at a time of a given type
975 let countMyChalls = 0;
976 let challToDelIdx = 0;
977 let oldestAdded = Number.MAX_SAFE_INTEGER;
978 for (let i=0; i<this.challenges.length; i++) {
979 const c = this.challenges[i];
982 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
985 if (c.added < oldestAdded) {
987 oldestAdded = c.added;
991 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
994 { data: { cid: this.challenges[challToDelIdx].id } }
996 if (ctype == "corr") {
1000 { data: { id: this.challenges[challToDelIdx].id } }
1003 this.challenges.splice(challToDelIdx, 1);
1005 this.send("newchallenge", {
1006 data: Object.assign({ from: this.st.user.sid }, chall)
1008 // Add new challenge:
1010 sid: this.st.user.sid,
1011 id: this.st.user.id,
1012 name: this.st.user.name
1014 chall.added = Date.now();
1015 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
1017 chall.vname = this.newchallenge.vname;
1018 this.challenges.push(chall);
1019 // Remember cadence + vid for quicker further challenges:
1020 localStorage.setItem("cadence", chall.cadence);
1021 localStorage.setItem("vid", chall.vid);
1022 localStorage.setItem("challRandomness", chall.randomness);
1023 document.getElementById("modalNewgame").checked = false;
1024 // Show the challenge if not on current display
1026 (ctype == "live" && this.cdisplay == "corr") ||
1027 (ctype == "corr" && this.cdisplay == "live")
1029 this.setDisplay('c', ctype);
1032 if (ctype == "live") {
1033 // Live challenges have a random ID
1034 finishAddChallenge(null);
1036 // Correspondance game: send challenge to server
1041 data: { chall: chall },
1042 success: (response) => {
1043 finishAddChallenge(response.id);
1049 // Callback function after a diagram was showed to accept
1050 // or refuse targetted challenge:
1051 decisionChallenge: function(accepted) {
1052 this.curChallToAccept.accepted = accepted;
1053 this.finishProcessingChallenge(this.curChallToAccept);
1054 document.getElementById("modalAccept").checked = false;
1056 finishProcessingChallenge: function(c) {
1059 sid: this.st.user.sid,
1060 id: this.st.user.id,
1061 name: this.st.user.name
1064 if (c.type == "live")
1065 // Remove all live challenges of both players
1066 this.send("deletechallenge_s", { data: { sids: [c.from.sid, c.seat.sid] } });
1068 // Corr challenge: just remove the challenge
1069 this.send("deletechallenge_s", { data: { cid: c.id } });
1071 const oppsid = this.getOppsid(c);
1073 this.send("refusechallenge", { data: c.id, target: oppsid });
1074 if (c.type == "corr") {
1078 { data: { id: c.id } }
1081 this.send("deletechallenge_s", { data: { cid: c.id } });
1084 // TODO: if several players click same challenge at the same time: problem
1085 clickChallenge: async function(c) {
1087 c.from.sid == this.st.user.sid || //live
1088 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1090 if (c.type == "corr" && this.st.user.id <= 0) {
1091 alert(this.st.tr["Please log in to accept corr challenges"]);
1095 await import("@/variants/" + c.vname + ".js")
1096 .then((vModule) => {
1097 window.V = vModule[c.vname + "Rules"];
1099 // c.to == this.st.user.name (connected)
1101 const parsedFen = V.ParseFen(c.fen);
1102 c.mycolor = V.GetOppCol(parsedFen.turn);
1103 this.tchallDiag = getDiagram({
1104 position: parsedFen.position,
1105 orientation: c.mycolor
1108 this.curChallToAccept = c;
1109 document.getElementById("modalAccept").checked = true;
1111 else this.finishProcessingChallenge(c);
1116 if (c.type == "corr") {
1120 { data: { id: c.id } }
1123 this.send("deletechallenge_s", { data: { cid: c.id } });
1125 // In all cases, the challenge is consumed:
1126 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1128 // NOTE: when launching game, the challenge is already being deleted
1129 launchGame: function(c) {
1130 // White player index 0, black player index 1:
1133 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1134 : shuffle([c.from, c.seat]);
1135 // These game informations will be shared
1137 id: getRandString(),
1138 fen: c.fen || V.GenRandInitFen(c.randomness),
1139 randomness: c.randomness, //for rematch
1144 const notifyNewgame = () => {
1145 const oppsid = this.getOppsid(c);
1147 // Opponent is online
1148 this.send("startgame", { data: gameInfo, target: oppsid });
1149 // If new corr game, notify Hall (except opponent and me)
1150 if (c.type == "corr") {
1155 excluded: [this.st.user.sid, oppsid]
1159 // Notify MyGames page:
1164 targets: gameInfo.players
1167 // NOTE: no need to send the game to the room, since I'll connect
1168 // on game just after, the main Hall will be notified.
1170 if (c.type == "live") {
1172 this.startNewGame(gameInfo);
1174 // corr: game only on server
1179 // cid is useful to delete the challenge:
1184 success: (response) => {
1185 gameInfo.id = response.id;
1187 this.$router.push("/game/" + response.id);
1193 // NOTE: for live games only (corr games start on the server)
1194 startNewGame: function(gameInfo) {
1195 const game = Object.assign(
1199 // (other) Game infos: constant
1200 fenStart: gameInfo.fen,
1201 vname: this.getVname(gameInfo.vid),
1202 created: Date.now(),
1203 // Game state (including FEN): will be updated
1205 clocks: [-1, -1], //-1 = unstarted
1211 GameStorage.add(game, (err) => {
1212 // If an error occurred, game is not added: a tab already
1213 // added the game. Maybe a focused one, maybe not.
1214 // We know for sure that it emitted the gong start sound.
1215 // ==> Do not play it again.
1216 if (!err && this.st.settings.sound)
1217 new Audio("/sounds/newgame.flac").play().catch(() => {});
1218 this.$router.push("/game/" + gameInfo.id);
1221 document.hidden ? 500 + 1000 * Math.random() : 0
1228 <style lang="sass" scoped>
1236 #newgameDiv > .card, #acceptDiv > .card
1240 div#peopleWrap > .card
1243 @media screen and (min-width: 1281px)
1244 div#peopleWrap > .card
1247 @media screen and (max-width: 1280px)
1248 div#peopleWrap > .card
1251 @media screen and (max-width: 767px)
1252 div#peopleWrap > .card
1265 @media screen and (max-width: 767px)
1280 button.player-action
1284 background-color: #c5fefe !important
1287 background-color: #f9faee
1290 background-color: lightgreen
1292 background-color: red
1295 // margin-top set dynamically (depends if diagram showed or not)
1306 // width: 100% required for Firefox
1314 @media screen and (max-width: 767px)
1320 background-color: #FF5733
1322 background-color: #2B63B4
1324 background-color: #33B42B
1326 @media screen and (max-width: 767px)
1335 background-color: lightgrey