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)"
88 v-model="newchallenge.to"
90 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
93 @input="trySetNewchallDiag()"
95 v-model="newchallenge.fen"
97 .diagram(v-html="newchallenge.diag")
98 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
99 input#modalPeople.modal(
101 @click="resetSocialColor()"
105 data-checkbox="modalPeople"
108 label.modal-close(for="modalPeople")
112 v-for="sid in Object.keys(people)"
113 v-if="!!people[sid].name"
115 span {{ people[sid].name }}
116 button.player-action(
118 @click="watchGame(sid)"
120 | {{ st.tr["Observe"] }}
121 button.player-action(
122 v-else-if="isFocusedOnHall(sid)"
123 @click="challenge(sid)"
125 | {{ st.tr["Challenge"] }}
126 p.anonymous @nonymous ({{ anonymousCount() }})
130 @mychat="processChat"
135 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
137 button#peopleBtn(@click="openModalPeople()")
138 | {{ st.tr["Who's there?"] }}
139 button(@click="showNewchallengeForm()")
140 | {{ st.tr["New game"] }}
141 .row(v-if="presetChalls.length > 0")
142 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
143 h4.text-center {{ st.tr["Preset challenges"] }}
147 th {{ st.tr["Variant"] }}
148 th {{ st.tr["Cadence"] }}
149 th {{ st.tr["Random?"] }}
153 v-for="pc in presetChalls"
154 @click="newChallFromPreset(pc)"
158 td(:class="getRandomnessClass(pc)")
159 td.remove-preset(@click="removePresetChall($event, pc)")
160 img(src="/images/icons/delete.svg")
162 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
165 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
166 | {{ st.tr["Live challenges"] }}
167 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
168 | {{ st.tr["Correspondance challenges"] }}
170 v-show="cdisplay=='live'"
171 :challenges="filterChallenges('live')"
172 @click-challenge="clickChallenge"
175 v-show="cdisplay=='corr'"
176 :challenges="filterChallenges('corr')"
177 @click-challenge="clickChallenge"
181 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
182 | {{ st.tr["Live games"] }}
183 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
184 | {{ st.tr["Correspondance games"] }}
186 v-show="gdisplay=='live'"
187 :games="filterGames('live')"
189 @show-game="showGame"
191 div(v-show="gdisplay=='corr'")
193 :games="filterGames('corr')"
195 @show-game="showGame"
199 @click="loadMoreCorr()"
201 | {{ st.tr["Load more"] }}
205 import { store } from "@/store";
206 import { checkChallenge } from "@/data/challengeCheck";
207 import { ArrayFun } from "@/utils/array";
208 import { ajax } from "@/utils/ajax";
209 import params from "@/parameters";
210 import { getRandString, shuffle } from "@/utils/alea";
211 import { getDiagram } from "@/utils/printDiagram";
212 import Chat from "@/components/Chat.vue";
213 import GameList from "@/components/GameList.vue";
214 import ChallengeList from "@/components/ChallengeList.vue";
215 import { GameStorage } from "@/utils/gameStorage";
216 import { processModalClick } from "@/utils/modalClick";
227 cdisplay: "live", //or corr
229 // timestamp of last showed (oldest) corr game:
230 cursor: Number.MAX_SAFE_INTEGER,
231 // hasMore == TRUE: a priori there could be more games to load
239 vid: parseInt(localStorage.getItem("vid")) || 0,
240 to: "", //name of challenged player (if any)
241 cadence: localStorage.getItem("cadence") || "",
242 randomness: parseInt(localStorage.getItem("challRandomness")) || 2,
243 // VariantRules object, stored to not interfere with
244 // diagrams of targetted challenges:
247 diag: "", //visualizing FEN
248 memorize: false //put settings in localStorage
251 curChallToAccept: {from: {}},
252 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
255 // Related to (killing of) self multi-connects:
261 // st.variants changes only once, at loading from [] to [...]
262 "st.variants": function() {
263 // Set potential challenges and games variant names:
264 this.challenges.concat(this.games).forEach(o => {
265 if (!o.vname) o.vname = this.getVname(o.vid);
267 if (!this.newchallenge.V && this.newchallenge.vid > 0)
268 this.loadNewchallVariant();
271 created: function() {
272 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
273 this.loadNewchallVariant();
274 const my = this.st.user;
281 pages: [{ path: "/", focus: true }]
284 const connectAndPoll = () => {
285 this.send("connect");
286 this.send("pollclientsandgamers");
288 // Initialize connection
289 this.connexionString =
298 // Hall: path is "/" (could be hard-coded as well)
299 encodeURIComponent(this.$route.path);
300 this.conn = new WebSocket(this.connexionString);
301 this.conn.onopen = connectAndPoll;
302 this.conn.addEventListener("message", this.socketMessageListener);
303 this.conn.addEventListener("close", this.socketCloseListener);
305 mounted: function() {
306 document.addEventListener('visibilitychange', this.visibilityChange);
307 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
308 document.getElementById(eltName)
309 .addEventListener("click", processModalClick);
311 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
312 b.addEventListener("click", () => {
313 this.newchallenge.cadence = b.innerHTML;
316 const dispCorr = this.$route.query["disp"];
318 dispCorr || localStorage.getItem("type-challenges") || "live";
320 dispCorr || localStorage.getItem("type-games") || "live";
321 this.setDisplay('c', showCtype);
322 this.setDisplay('g', showGtype);
323 // Ask server for current corr games (all but mines)
325 // Also ask for corr challenges (open + sent by/to me)
326 // List them all, because they are not supposed to be that many (TODO?)
331 data: { uid: this.st.user.id },
332 success: (response) => {
334 response.challenges.length > 0 &&
335 this.challenges.length == 0 &&
336 this.cdisplay == "live"
339 .getElementById("btnCcorr")
340 .classList.add("somethingnew");
342 // Gather all senders names, and then retrieve full identity:
343 // (TODO [perf]: some might be online...)
345 response.challenges.forEach(c => {
346 if (c.uid != this.st.user.id) names[c.uid] = "";
347 else if (!!c.target && c.target != this.st.user.id)
348 names[c.target] = "";
350 const addChallenges = () => {
351 names[this.st.user.id] = this.st.user.name; //in case of
352 this.challenges = this.challenges.concat(
353 response.challenges.map(c => {
354 const from = { name: names[c.uid], id: c.uid }; //or just name
355 const type = this.classifyObject(c);
356 const vname = this.getVname(c.vid);
357 return Object.assign(
363 to: c.target ? names[c.target] : ""
370 if (Object.keys(names).length > 0) {
375 data: { ids: Object.keys(names).join(",") },
376 success: (response2) => {
377 response2.users.forEach(u => {
378 names[u.id] = u.name;
384 } else addChallenges();
389 beforeDestroy: function() {
390 document.removeEventListener('visibilitychange', this.visibilityChange);
391 this.send("disconnect");
394 getRandomnessClass: function(pc) {
396 ["random-" + pc.randomness]: true
399 openModalPeople: function() {
400 window.doClick("modalPeople");
401 document.getElementById("inputChat").focus();
403 anonymousCount: function() {
405 Object.values(this.people).forEach(p => {
406 // Do not cound people who did not send their identity yet:
407 count += (!p.name && p.id === 0) ? 1 : 0;
411 visibilityChange: function() {
412 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
414 document.visibilityState == "visible"
419 partialResetNewchallenge: function() {
420 // Reset potential target and custom FEN:
421 this.newchallenge.to = "";
422 this.newchallenge.fen = "";
423 this.newchallenge.diag = "";
424 this.newchallenge.memorize = false;
426 showNewchallengeForm: function() {
427 this.partialResetNewchallenge();
428 window.doClick("modalNewgame");
430 addPresetChall: function(chall) {
431 // Add only if not already existing:
432 if (this.presetChalls.some(c =>
433 c.vid == chall.vid &&
434 c.cadence == chall.cadence &&
435 c.randomness == chall.randomness
439 const L = this.presetChalls.length;
440 this.presetChalls.push({
443 vname: chall.vname, //redundant, but easier
444 cadence: chall.cadence,
445 randomness: chall.randomness
447 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
449 removePresetChall: function(e, pchall) {
451 const pchallIdx = this.presetChalls.findIndex(pc => pc.index == pchall.index);
452 this.presetChalls.splice(pchallIdx, 1);
453 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
455 tchallButtonsMargin: function() {
456 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
459 changeChallTarget: function() {
460 if (!this.newchallenge.to) {
461 // Reset potential FEN + diagram
462 this.newchallenge.fen = "";
463 this.newchallenge.diag = "";
466 cadenceFocusIfOpened: function() {
467 if (event.target.checked)
468 document.getElementById("cadence").focus();
470 send: function(code, obj) {
472 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
475 getVname: function(vid) {
476 const variant = this.st.variants.find(v => v.id == vid);
477 // this.st.variants might be uninitialized (variant == null)
478 return variant ? variant.name : "";
480 filterChallenges: function(type) {
481 return this.challenges.filter(c => c.type == type);
483 filterGames: function(type) {
484 return this.games.filter(g => g.type == type);
486 classifyObject: function(o) {
487 // o: challenge or game
488 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
490 setDisplay: function(letter, type, e) {
491 this[letter + "display"] = type;
492 localStorage.setItem(
493 "type-" + (letter == "c" ? "challenges" : "games"),
498 : document.getElementById("btn" + letter.toUpperCase() + type);
499 elt.classList.add("active");
500 elt.classList.remove("somethingnew"); //in case of
501 if (!!elt.previousElementSibling)
502 elt.previousElementSibling.classList.remove("active");
503 else elt.nextElementSibling.classList.remove("active");
505 isGamer: function(sid) {
506 return this.people[sid].pages
507 .some(p => p.focus && p.path.indexOf("/game/") >= 0);
509 isFocusedOnHall: function(sid) {
511 // This is meant to challenge people, thus the next 2 conditions:
512 this.st.user.id > 0 &&
513 sid != this.st.user.sid &&
514 this.people[sid].pages.some(p => p.path == "/" && p.focus)
517 challenge: function(sid) {
518 this.partialResetNewchallenge();
519 // Available, in Hall
520 this.newchallenge.to = this.people[sid].name;
521 // TODO: also store target sid to not re-search for it
522 document.getElementById("modalPeople").checked = false;
523 window.doClick("modalNewgame");
525 watchGame: function(sid) {
526 // In some game, maybe playing maybe not: show a random one
528 this.people[sid].pages.forEach(p => {
530 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
531 if (!!matchGid) gids.push(matchGid[0]);
534 const gid = gids[Math.floor(Math.random() * gids.length)];
535 const game = this.games.find(g => g.id == gid);
536 if (!!game) this.showGame(game);
537 else this.$router.push("/game/" + gid); //game vs. me
539 showGame: function(g) {
540 // NOTE: we are an observer, since only games I don't play are shown here
541 // ==> Moves sent by connected remote player(s) if live game
542 this.$router.push("/game/" + g.id);
544 resetSocialColor: function() {
545 // TODO: this is called twice, once on opening an once on closing
546 document.getElementById("peopleBtn").classList.remove("somethingnew");
548 processChat: function(chat) {
549 this.send("newchat", { data: chat });
551 getOppsid: function(c) {
552 let oppsid = c.from.sid; //may not be defined if corr + offline opp
554 oppsid = Object.keys(this.people).find(
555 sid => this.people[sid].id == c.from.id
561 socketMessageListener: function(msg) {
562 if (!this.conn) return;
563 const data = JSON.parse(msg.data);
565 case "pollclientsandgamers": {
566 // Since people can be both in Hall and Game,
567 // need to track "askIdentity" requests:
568 let identityAsked = {};
569 // TODO: shuffling and random filtering on server, if
570 // the room is really crowded.
571 data.sockIds.forEach(s => {
572 const page = s.page || "/";
573 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
574 this.send("askidentity", { target: s.sid, page: page });
575 identityAsked[s.sid] = true;
577 if (!this.people[s.sid]) {
578 // Do not set name or id: identity unknown yet
579 this.people[s.sid] = { pages: [{path: page, focus: true}] };
581 else if (!(this.people[s.sid].pages.find(p => p.path == page)))
582 this.people[s.sid].pages.push({ path: page, focus: true });
585 this.send("askchallenges", { target: s.sid });
586 // Peer is in Game: ask only if live game
587 else if (!page.match(/\/[0-9]+$/))
588 this.send("askgame", { target: s.sid, page: page });
594 const page = data.page || "/";
595 if (data.code == "connect") {
596 // Ask challenges only on first connexion:
597 if (!this.people[data.from])
598 this.send("askchallenges", { target: data.from });
600 // Ask game only if live:
601 else if (!page.match(/\/[0-9]+$/))
602 this.send("askgame", { target: data.from, page: page });
603 if (!this.people[data.from])
604 this.people[data.from] = { pages: [{ path: page, focus: true }] };
606 // Append page if not already in list
607 if (!(this.people[data.from].pages.find(p => p.path == page)))
608 this.people[data.from].pages.push({ path: page, focus: true });
610 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
611 // Identity not known yet
612 this.newConnect[data.from] = true; //for self multi-connects tests
613 this.send("askidentity", { target: data.from, page: page });
618 case "gdisconnect": {
619 // If the user reloads the page twice very quickly (experienced with Firefox),
620 // the first reload won't have time to connect but will trigger a "close" event anyway.
621 // ==> Next check is required.
622 if (!this.people[data.from]) return;
623 const page = data.page || "/";
624 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
625 if (this.people[data.from].pages.length == 0)
626 this.$delete(this.people, data.from);
627 // Disconnect means no more tmpIds:
628 if (data.code == "disconnect") {
629 // Remove the live challenges sent by this player:
632 c => c.type == "live" && c.from.sid == data.from,
636 // Remove the matching live game if now unreachable
637 const gid = page.match(/[a-zA-Z0-9]+$/)[0];
638 // Corr games are always reachable:
639 if (!gid.match(/^[0-9]+$/)) {
640 // Live games are reachable as long as someone is on the game page
641 if (Object.values(this.people).every(p =>
642 p.pages.every(pg => pg.path != page))) {
643 ArrayFun.remove(this.games, g => g.id == gid);
650 // If user reload a page, focus may arrive earlier than connect
651 if (!!this.people[data.from]) {
652 this.people[data.from].pages
653 .find(p => p.path == data.page).focus = true;
654 this.$forceUpdate(); //TODO: shouldn't be required
658 if (!!this.people[data.from]) {
659 this.people[data.from].pages
660 .find(p => p.path == data.page).focus = false;
661 this.$forceUpdate(); //TODO: shouldn't be required
665 // I logged in elsewhere:
666 this.conn.removeEventListener("message", this.socketMessageListener);
667 this.conn.removeEventListener("close", this.socketCloseListener);
669 alert(this.st.tr["New connexion detected: tab now offline"]);
671 case "askidentity": {
672 // Request for identification
674 // Decompose to avoid revealing email
675 name: this.st.user.name,
676 sid: this.st.user.sid,
679 this.send("identity", { data: me, target: data.from });
683 const user = data.data;
684 let player = this.people[user.sid];
685 // player.pages is already set
687 player.name = user.name;
688 // TODO: this.$set(people, ...) fails. So forceUpdate.
689 // But this shouldn't be like that!
691 // If I multi-connect, kill current connexion if no mark (I'm older)
692 if (this.newConnect[user.sid]) {
695 user.id == this.st.user.id &&
696 user.sid != this.st.user.sid &&
697 !this.killed[this.st.user.sid]
699 this.send("killme", { sid: this.st.user.sid });
700 this.killed[this.st.user.sid] = true;
702 delete this.newConnect[user.sid];
706 case "askchallenges": {
707 // Send my current live challenges (if any)
708 const myChallenges = this.challenges
710 c.from.sid == this.st.user.sid && c.type == "live"
713 // NOTE: in principle, should only send targeted challenge to the target.
714 // But we may not know yet the identity of the target (just name),
715 // so cannot decide if data.from is the target or not.
718 from: this.st.user.sid,
720 randomness: c.randomness,
727 if (myChallenges.length > 0)
728 this.send("challenges", { data: myChallenges, target: data.from });
731 case "challenges": //after "askchallenges"
732 data.data.forEach(this.addChallenge);
735 this.addChallenge(data.data);
737 case "refusechallenge": {
738 const cid = data.data;
739 ArrayFun.remove(this.challenges, c => c.id == cid);
740 alert(this.st.tr["Challenge declined"]);
743 case "deletechallenge_s": {
744 // NOTE: the challenge(s) may be already removed
745 const cref = data.data;
746 if (!!cref.cid) ArrayFun.remove(this.challenges, c => c.id == cref.cid);
747 else if (!!cref.sids) {
748 cref.sids.forEach(s => {
751 c => c.type == "live" && c.from.sid == s,
758 case "game": // Individual request
760 const game = data.data;
761 // Ignore games where I play (will go in MyGames page),
762 // and also games that I already received.
764 game.players.every(p =>
765 p.sid != this.st.user.sid && p.id != this.st.user.id) &&
766 this.games.findIndex(g => g.id == game.id) == -1
769 newGame.type = this.classifyObject(game);
770 newGame.vname = this.getVname(game.vid);
772 // New game from Hall
774 this.games.push(newGame);
776 (newGame.type == "live" && this.gdisplay == "corr") ||
777 (newGame.type == "corr" && this.gdisplay == "live")
780 .getElementById("btnG" + newGame.type)
781 .classList.add("somethingnew");
787 let g = this.games.find(g => g.id == data.gid);
788 if (!!g) g.score = data.score;
792 // New game just started, I'm involved
793 const gameInfo = data.data;
794 if (this.classifyObject(gameInfo) == "live")
795 this.startNewGame(gameInfo);
798 this.st.tr["New correspondance game:"] +
799 " <a href='#/game/" +
805 document.getElementById("modalInfo").checked = true;
810 this.$refs["chatcomp"].newChat(data.data);
811 if (!document.getElementById("modalPeople").checked)
812 document.getElementById("peopleBtn").classList.add("somethingnew");
816 socketCloseListener: function() {
817 if (!this.conn) return;
818 this.conn = new WebSocket(this.connexionString);
819 this.conn.addEventListener("message", this.socketMessageListener);
820 this.conn.addEventListener("close", this.socketCloseListener);
822 loadMoreCorr: function() {
828 uid: this.st.user.id,
832 const L = res.games.length;
835 this.cursor == Number.MAX_SAFE_INTEGER &&
836 this.games.length == 0 &&
837 this.gdisplay == "live"
839 // First loading: show indicators
841 .getElementById("btnGcorr")
842 .classList.add("somethingnew");
844 this.cursor = res.games[L - 1].created;
845 let moreGames = res.games.map(g => {
846 const vname = this.getVname(g.vid);
847 return Object.assign(
856 this.games = this.games.concat(moreGames);
857 } else this.hasMore = false;
862 // Challenge lifecycle:
863 addChallenge: function(chall) {
864 // NOTE about next condition: see "askchallenges" case.
867 (this.people[chall.from].id > 0 &&
868 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
870 let newChall = Object.assign({}, chall);
871 newChall.type = this.classifyObject(chall);
872 newChall.randomness = chall.randomness;
873 newChall.added = Date.now();
874 let fromValues = Object.assign({}, this.people[chall.from]);
875 delete fromValues["pages"]; //irrelevant in this context
876 newChall.from = Object.assign({ sid: chall.from }, fromValues);
877 newChall.vname = this.getVname(newChall.vid);
878 this.challenges.push(newChall);
880 (newChall.type == "live" && this.cdisplay == "corr") ||
881 (newChall.type == "corr" && this.cdisplay == "live")
884 .getElementById("btnC" + newChall.type)
885 .classList.add("somethingnew");
889 loadNewchallVariant: async function(cb) {
890 const vname = this.getVname(this.newchallenge.vid);
891 await import("@/variants/" + vname + ".js")
893 window.V = vModule[vname + "Rules"];
894 this.newchallenge.V = window.V;
895 this.newchallenge.vname = vname;
899 trySetNewchallDiag: function() {
900 if (!this.newchallenge.fen) {
901 this.newchallenge.diag = "";
904 // If vid > 0 then the variant is loaded (function above):
905 window.V = this.newchallenge.V;
907 this.newchallenge.vid > 0 &&
908 !!this.newchallenge.fen &&
909 V.IsGoodFen(this.newchallenge.fen)
911 const parsedFen = V.ParseFen(this.newchallenge.fen);
912 this.newchallenge.diag = getDiagram({
913 position: parsedFen.position,
914 orientation: parsedFen.turn
916 } else this.newchallenge.diag = "";
918 newChallFromPreset(pchall) {
919 this.partialResetNewchallenge();
920 this.newchallenge.vid = pchall.vid;
921 this.newchallenge.cadence = pchall.cadence;
922 this.newchallenge.randomness = pchall.randomness;
923 this.loadNewchallVariant(this.issueNewChallenge);
925 issueNewChallenge: async function() {
926 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
927 this.newchallenge.cadence += "+0"; //assume minutes, no increment
928 const ctype = this.classifyObject(this.newchallenge);
929 // TODO: cadence still unchecked so ctype could be wrong...
931 if (!this.newchallenge.vid)
932 error = this.st.tr["Please select a variant"];
933 else if (ctype == "corr" && this.st.user.id <= 0)
934 error = this.st.tr["Please log in to play correspondance games"];
935 else if (!!this.newchallenge.to) {
936 if (this.newchallenge.to == this.st.user.name)
937 error = this.st.tr["Self-challenge is forbidden"];
940 Object.values(this.people).every(p => p.name != this.newchallenge.to)
942 error = this.newchallenge.to + " " + this.st.tr["is not online"];
949 window.V = this.newchallenge.V;
950 error = checkChallenge(this.newchallenge);
955 // NOTE: "from" information is not required here
956 let chall = Object.assign({}, this.newchallenge);
957 // Add only if not already issued (not counting target or FEN):
958 if (this.challenges.some(c =>
959 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
960 c.vid == chall.vid &&
961 c.cadence == chall.cadence &&
962 c.randomness == chall.randomness
964 alert(this.st.tr["Challenge already exists"]);
967 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
969 delete chall["diag"];
970 const finishAddChallenge = cid => {
971 chall.id = cid || "c" + getRandString();
972 const MAX_ALLOWED_CHALLS = 3;
973 // Remove oldest challenge if 3 found: only 3 at a time of a given type
974 let countMyChalls = 0;
975 let challToDelIdx = 0;
976 let oldestAdded = Number.MAX_SAFE_INTEGER;
977 for (let i=0; i<this.challenges.length; i++) {
978 const c = this.challenges[i];
981 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
984 if (c.added < oldestAdded) {
986 oldestAdded = c.added;
990 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
993 { data: { cid: this.challenges[challToDelIdx].id } }
995 if (ctype == "corr") {
999 { data: { id: this.challenges[challToDelIdx].id } }
1002 this.challenges.splice(challToDelIdx, 1);
1004 this.send("newchallenge", {
1005 data: Object.assign({ from: this.st.user.sid }, chall)
1007 // Add new challenge:
1009 sid: this.st.user.sid,
1010 id: this.st.user.id,
1011 name: this.st.user.name
1013 chall.added = Date.now();
1014 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
1016 chall.vname = this.newchallenge.vname;
1017 this.challenges.push(chall);
1018 // Remember cadence + vid for quicker further challenges:
1019 localStorage.setItem("cadence", chall.cadence);
1020 localStorage.setItem("vid", chall.vid);
1021 localStorage.setItem("challRandomness", chall.randomness);
1022 document.getElementById("modalNewgame").checked = false;
1023 // Show the challenge if not on current display
1025 (ctype == "live" && this.cdisplay == "corr") ||
1026 (ctype == "corr" && this.cdisplay == "live")
1028 this.setDisplay('c', ctype);
1031 if (ctype == "live") {
1032 // Live challenges have a random ID
1033 finishAddChallenge(null);
1035 // Correspondance game: send challenge to server
1040 data: { chall: chall },
1041 success: (response) => {
1042 finishAddChallenge(response.id);
1048 // Callback function after a diagram was showed to accept
1049 // or refuse targetted challenge:
1050 decisionChallenge: function(accepted) {
1051 this.curChallToAccept.accepted = accepted;
1052 this.finishProcessingChallenge(this.curChallToAccept);
1053 document.getElementById("modalAccept").checked = false;
1055 finishProcessingChallenge: function(c) {
1058 sid: this.st.user.sid,
1059 id: this.st.user.id,
1060 name: this.st.user.name
1063 if (c.type == "live")
1064 // Remove all live challenges of both players
1065 this.send("deletechallenge_s", { data: { sids: [c.from.sid, c.seat.sid] } });
1067 // Corr challenge: just remove the challenge
1068 this.send("deletechallenge_s", { data: { cid: c.id } });
1070 const oppsid = this.getOppsid(c);
1072 this.send("refusechallenge", { data: c.id, target: oppsid });
1073 if (c.type == "corr") {
1077 { data: { id: c.id } }
1080 this.send("deletechallenge_s", { data: { cid: c.id } });
1083 // TODO: if several players click same challenge at the same time: problem
1084 clickChallenge: async function(c) {
1086 c.from.sid == this.st.user.sid || //live
1087 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1089 if (c.type == "corr" && this.st.user.id <= 0) {
1090 alert(this.st.tr["Please log in to accept corr challenges"]);
1094 await import("@/variants/" + c.vname + ".js")
1095 .then((vModule) => {
1096 window.V = vModule[c.vname + "Rules"];
1098 // c.to == this.st.user.name (connected)
1100 const parsedFen = V.ParseFen(c.fen);
1101 c.mycolor = V.GetOppCol(parsedFen.turn);
1102 this.tchallDiag = getDiagram({
1103 position: parsedFen.position,
1104 orientation: c.mycolor
1107 this.curChallToAccept = c;
1108 document.getElementById("modalAccept").checked = true;
1110 else this.finishProcessingChallenge(c);
1115 if (c.type == "corr") {
1119 { data: { id: c.id } }
1122 this.send("deletechallenge_s", { data: { cid: c.id } });
1124 // In all cases, the challenge is consumed:
1125 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1127 // NOTE: when launching game, the challenge is already being deleted
1128 launchGame: function(c) {
1129 // White player index 0, black player index 1:
1132 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1133 : shuffle([c.from, c.seat]);
1134 // These game informations will be shared
1136 id: getRandString(),
1137 fen: c.fen || V.GenRandInitFen(c.randomness),
1138 randomness: c.randomness, //for rematch
1143 const notifyNewgame = () => {
1144 const oppsid = this.getOppsid(c);
1146 // Opponent is online
1147 this.send("startgame", { data: gameInfo, target: oppsid });
1148 // If new corr game, notify Hall (except opponent and me)
1149 if (c.type == "corr") {
1154 excluded: [this.st.user.sid, oppsid]
1158 // Notify MyGames page:
1163 targets: gameInfo.players
1166 // NOTE: no need to send the game to the room, since I'll connect
1167 // on game just after, the main Hall will be notified.
1169 if (c.type == "live") {
1171 this.startNewGame(gameInfo);
1173 // corr: game only on server
1178 // cid is useful to delete the challenge:
1183 success: (response) => {
1184 gameInfo.id = response.id;
1186 this.$router.push("/game/" + response.id);
1192 // NOTE: for live games only (corr games start on the server)
1193 startNewGame: function(gameInfo) {
1194 const game = Object.assign(
1198 // (other) Game infos: constant
1199 fenStart: gameInfo.fen,
1200 vname: this.getVname(gameInfo.vid),
1201 created: Date.now(),
1202 // Game state (including FEN): will be updated
1204 clocks: [-1, -1], //-1 = unstarted
1210 GameStorage.add(game, (err) => {
1211 // If an error occurred, game is not added: a tab already
1212 // added the game. Maybe a focused one, maybe not.
1213 // We know for sure that it emitted the gong start sound.
1214 // ==> Do not play it again.
1215 if (!err && this.st.settings.sound)
1216 new Audio("/sounds/newgame.flac").play().catch(() => {});
1217 this.$router.push("/game/" + gameInfo.id);
1220 document.hidden ? 500 + 1000 * Math.random() : 0
1227 <style lang="sass" scoped>
1235 #newgameDiv > .card, #acceptDiv > .card
1239 div#peopleWrap > .card
1242 @media screen and (min-width: 1281px)
1243 div#peopleWrap > .card
1246 @media screen and (max-width: 1280px)
1247 div#peopleWrap > .card
1250 @media screen and (max-width: 767px)
1251 div#peopleWrap > .card
1264 @media screen and (max-width: 767px)
1279 button.player-action
1283 background-color: #c5fefe !important
1286 background-color: #f9faee
1289 background-color: lightgreen
1291 background-color: red
1294 // margin-top set dynamically (depends if diagram showed or not)
1305 // width: 100% required for Firefox
1313 @media screen and (max-width: 767px)
1319 background-color: #FF5733
1321 background-color: #2B63B4
1323 background-color: #33B42B
1325 @media screen and (max-width: 767px)
1334 background-color: lightgrey