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?"] }}
78 v-model="newchallenge.to"
80 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
83 @input="trySetNewchallDiag()"
85 v-model="newchallenge.fen"
87 .diagram(v-html="newchallenge.diag")
88 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
89 input#modalPeople.modal(
91 @click="resetSocialColor()"
95 data-checkbox="modalPeople"
98 label.modal-close(for="modalPeople")
102 v-for="sid in Object.keys(people)"
103 v-if="!!people[sid].name"
105 span {{ people[sid].name }}
106 button.player-action(
108 @click="watchGame(sid)"
110 | {{ st.tr["Observe"] }}
111 button.player-action(
112 v-else-if="isFocusedOnHall(sid)"
113 @click="challenge(sid)"
115 | {{ st.tr["Challenge"] }}
116 p.anonymous @nonymous ({{ anonymousCount }})
120 @mychat="processChat"
125 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
127 button#peopleBtn(onClick="window.doClick('modalPeople')")
128 | {{ st.tr["Who's there?"] }}
129 button(@click="showNewchallengeForm()")
130 | {{ st.tr["New game"] }}
131 .row(v-if="presetChalls.length > 0")
132 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
133 h4.text-center {{ st.tr["Preset challenges"] }}
137 th {{ st.tr["Variant"] }}
138 th {{ st.tr["Cadence"] }}
139 th {{ st.tr["Random?"] }}
143 v-for="pc in presetChalls"
144 @click="newChallFromPreset(pc)"
148 td(:class="getRandomnessClass(pc)")
149 td.remove-preset(@click="removePresetChall($event, pc)")
150 img(src="/images/icons/delete.svg")
152 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
155 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
156 | {{ st.tr["Live challenges"] }}
157 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
158 | {{ st.tr["Correspondance challenges"] }}
160 v-show="cdisplay=='live'"
161 :challenges="filterChallenges('live')"
162 @click-challenge="clickChallenge"
165 v-show="cdisplay=='corr'"
166 :challenges="filterChallenges('corr')"
167 @click-challenge="clickChallenge"
171 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
172 | {{ st.tr["Live games"] }}
173 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
174 | {{ st.tr["Correspondance games"] }}
176 v-show="gdisplay=='live'"
177 :games="filterGames('live')"
179 @show-game="showGame"
182 v-show="gdisplay=='corr'"
183 :games="filterGames('corr')"
185 @show-game="showGame"
190 import { store } from "@/store";
191 import { checkChallenge } from "@/data/challengeCheck";
192 import { ArrayFun } from "@/utils/array";
193 import { ajax } from "@/utils/ajax";
194 import params from "@/parameters";
195 import { getRandString, shuffle } from "@/utils/alea";
196 import { getDiagram } from "@/utils/printDiagram";
197 import Chat from "@/components/Chat.vue";
198 import GameList from "@/components/GameList.vue";
199 import ChallengeList from "@/components/ChallengeList.vue";
200 import { GameStorage } from "@/utils/gameStorage";
201 import { processModalClick } from "@/utils/modalClick";
212 cdisplay: "live", //or corr
220 vid: parseInt(localStorage.getItem("vid")) || 0,
221 to: "", //name of challenged player (if any)
222 cadence: localStorage.getItem("cadence") || "",
223 randomness: parseInt(localStorage.getItem("randomness")) || 2,
224 // VariantRules object, stored to not interfere with
225 // diagrams of targetted challenges:
228 diag: "", //visualizing FEN
229 memorize: false //put settings in localStorage
232 curChallToAccept: {from: {}},
233 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
237 // Related to (killing of) self multi-connects:
243 // st.variants changes only once, at loading from [] to [...]
244 "st.variants": function() {
245 // Set potential challenges and games variant names:
246 this.challenges.concat(this.games).forEach(o => {
247 if (!o.vname) o.vname = this.getVname(o.vid);
249 if (!this.newchallenge.V && this.newchallenge.vid > 0)
250 this.loadNewchallVariant();
254 anonymousCount: function() {
256 Object.values(this.people).forEach(p => {
257 // Do not cound people who did not send their identity yet:
258 count += (!p.name && p.id === 0) ? 1 : 0;
263 created: function() {
264 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
265 this.loadNewchallVariant();
266 const my = this.st.user;
273 pages: [{ path: "/", focus: true }]
276 // Ask server for current corr games (all but mines)
281 data: { uid: this.st.user.id, excluded: true },
282 success: (response) => {
283 this.games = this.games.concat(
284 response.games.map(g => {
285 const type = this.classifyObject(g);
286 const vname = this.getVname(g.vid);
287 return Object.assign(
300 // Also ask for corr challenges (open + sent by/to me)
305 data: { uid: this.st.user.id },
306 success: (response) => {
307 // Gather all senders names, and then retrieve full identity:
308 // (TODO [perf]: some might be online...)
310 response.challenges.forEach(c => {
311 if (c.uid != this.st.user.id) names[c.uid] = "";
312 else if (!!c.target && c.target != this.st.user.id)
313 names[c.target] = "";
315 const addChallenges = () => {
316 names[this.st.user.id] = this.st.user.name; //in case of
317 this.challenges = this.challenges.concat(
318 response.challenges.map(c => {
319 const from = { name: names[c.uid], id: c.uid }; //or just name
320 const type = this.classifyObject(c);
321 const vname = this.getVname(c.vid);
322 return Object.assign(
328 to: c.target ? names[c.target] : ""
335 if (Object.keys(names).length > 0) {
340 data: { ids: Object.keys(names).join(",") },
341 success: (response2) => {
342 response2.users.forEach(u => {
343 names[u.id] = u.name;
349 } else addChallenges();
353 const connectAndPoll = () => {
354 this.send("connect");
355 this.send("pollclientsandgamers");
357 // Initialize connection
358 this.connexionString =
367 // Hall: path is "/" (could be hard-coded as well)
368 encodeURIComponent(this.$route.path);
369 this.conn = new WebSocket(this.connexionString);
370 this.conn.onopen = connectAndPoll;
371 this.conn.onmessage = this.socketMessageListener;
372 this.conn.onclose = this.socketCloseListener;
374 mounted: function() {
375 document.addEventListener('visibilitychange', this.visibilityChange);
376 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
377 let elt = document.getElementById(eltName);
378 elt.addEventListener("click", processModalClick);
380 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
381 b.addEventListener("click", () => {
382 this.newchallenge.cadence = b.innerHTML;
385 const dispCorr = this.$route.query["disp"];
387 dispCorr || localStorage.getItem("type-challenges") || "live";
389 dispCorr || localStorage.getItem("type-games") || "live";
390 this.setDisplay("c", showCtype);
391 this.setDisplay("g", showGtype);
393 beforeDestroy: function() {
394 document.removeEventListener('visibilitychange', this.visibilityChange);
395 this.send("disconnect");
398 getRandomnessClass: function(pc) {
400 ["random-" + pc.randomness]: true
403 visibilityChange: function() {
404 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
406 document.visibilityState == "visible"
411 partialResetNewchallenge: function() {
412 // Reset potential target and custom FEN:
413 this.newchallenge.to = "";
414 this.newchallenge.fen = "";
415 this.newchallenge.diag = "";
416 this.newchallenge.memorize = false;
418 showNewchallengeForm: function() {
419 this.partialResetNewchallenge();
420 window.doClick("modalNewgame");
422 addPresetChall: function(chall) {
423 // Add only if not already existing:
424 if (this.presetChalls.some(c =>
425 c.vid == chall.vid &&
426 c.cadence == chall.cadence &&
427 c.randomness == chall.randomness
431 const L = this.presetChalls.length;
432 this.presetChalls.push({
435 vname: chall.vname, //redundant, but easier
436 cadence: chall.cadence,
437 randomness: chall.randomness
439 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
441 removePresetChall: function(e, pchall) {
443 const pchallIdx = this.presetChalls.findIndex(pc => pc.index == pchall.index);
444 this.presetChalls.splice(pchallIdx, 1);
445 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
447 tchallButtonsMargin: function() {
448 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
451 cadenceFocusIfOpened: function() {
452 if (event.target.checked)
453 document.getElementById("cadence").focus();
455 send: function(code, obj) {
457 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
460 getVname: function(vid) {
461 const variant = this.st.variants.find(v => v.id == vid);
462 // this.st.variants might be uninitialized (variant == null)
463 return variant ? variant.name : "";
465 filterChallenges: function(type) {
466 return this.challenges.filter(c => c.type == type);
468 filterGames: function(type) {
469 return this.games.filter(g => g.type == type);
471 classifyObject: function(o) {
472 // o: challenge or game
473 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
475 setDisplay: function(letter, type, e) {
476 this[letter + "display"] = type;
477 localStorage.setItem(
478 "type-" + (letter == "c" ? "challenges" : "games"),
483 : document.getElementById("btn" + letter.toUpperCase() + type);
484 elt.classList.add("active");
485 elt.classList.remove("somethingnew"); //in case of
486 if (!!elt.previousElementSibling)
487 elt.previousElementSibling.classList.remove("active");
488 else elt.nextElementSibling.classList.remove("active");
490 isGamer: function(sid) {
491 return this.people[sid].pages
492 .some(p => p.focus && p.path.indexOf("/game/") >= 0);
494 isFocusedOnHall: function(sid) {
496 // This is meant to challenge people, thus the next 2 conditions:
497 this.st.user.id > 0 &&
498 sid != this.st.user.sid &&
499 this.people[sid].pages.some(p => p.path == "/" && p.focus)
502 challenge: function(sid) {
503 this.partialResetNewchallenge();
504 // Available, in Hall
505 this.newchallenge.to = this.people[sid].name;
506 // TODO: also store target sid to not re-search for it
507 document.getElementById("modalPeople").checked = false;
508 window.doClick("modalNewgame");
510 watchGame: function(sid) {
511 // In some game, maybe playing maybe not: show a random one
513 this.people[sid].pages.forEach(p => {
515 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
516 if (!!matchGid) gids.push(matchGid[0]);
519 const gid = gids[Math.floor(Math.random() * gids.length)];
520 const game = this.games.find(g => g.id == gid);
521 if (!!game) this.showGame(game);
522 else this.$router.push("/game/" + gid); //game vs. me
524 showGame: function(g) {
525 // NOTE: we are an observer, since only games I don't play are shown here
526 // ==> Moves sent by connected remote player(s) if live game
527 let url = "/game/" + g.id;
528 if (g.type == "live")
529 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
530 this.$router.push(url);
532 resetSocialColor: function() {
533 // TODO: this is called twice, once on opening an once on closing
534 document.getElementById("peopleBtn").classList.remove("somethingnew");
536 processChat: function(chat) {
537 this.send("newchat", { data: chat });
539 getOppsid: function(c) {
540 let oppsid = c.from.sid; //may not be defined if corr + offline opp
542 oppsid = Object.keys(this.people).find(
543 sid => this.people[sid].id == c.from.id
549 socketMessageListener: function(msg) {
550 if (!this.conn) return;
551 const data = JSON.parse(msg.data);
553 case "pollclientsandgamers": {
554 // Since people can be both in Hall and Game,
555 // need to track "askIdentity" requests:
556 let identityAsked = {};
557 data.sockIds.forEach(s => {
558 const page = s.page || "/";
559 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
560 this.send("askidentity", { target: s.sid, page: page });
561 identityAsked[s.sid] = true;
563 if (!this.people[s.sid]) {
564 // Do not set name or id: identity unknown yet
565 this.people[s.sid] = { pages: [{path: page, focus: true}] };
567 else if (!(this.people[s.sid].pages.find(p => p.path == page)))
568 this.people[s.sid].pages.push({ path: page, focus: true });
571 this.send("askchallenges", { target: s.sid });
573 else this.send("askgame", { target: s.sid, page: page });
579 const page = data.page || "/";
580 // Only ask game / challenges if first connexion:
581 if (!this.people[data.from]) {
582 this.people[data.from] = { pages: [{ path: page, focus: true }] };
583 if (data.code == "connect")
584 this.send("askchallenges", { target: data.from });
585 else this.send("askgame", { target: data.from, page: page });
587 // Append page if not already in list
588 if (!(this.people[data.from].pages.find(p => p.path == page)))
589 this.people[data.from].pages.push({ path: page, focus: true });
591 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
592 // Identity not known yet
593 this.newConnect[data.from] = true; //for self multi-connects tests
594 this.send("askidentity", { target: data.from, page: page });
599 case "gdisconnect": {
600 // If the user reloads the page twice very quickly (experienced with Firefox),
601 // the first reload won't have time to connect but will trigger a "close" event anyway.
602 // ==> Next check is required.
603 if (!this.people[data.from]) return;
604 // Disconnect means no more tmpIds:
605 if (data.code == "disconnect") {
606 // Remove the live challenges sent by this player:
609 c => c.type == "live" && c.from.sid == data.from,
613 // Remove the matching live game if now unreachable
614 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
615 const gidx = this.games.findIndex(g => g.id == gid);
617 const game = this.games[gidx];
619 game.type == "live" &&
620 game.rids.length == 1 &&
621 game.rids[0] == data.from
623 this.games.splice(gidx, 1);
627 const page = data.page || "/";
628 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
629 if (this.people[data.from].pages.length == 0)
630 this.$delete(this.people, data.from);
634 // If user reload a page, focus may arrive earlier than connect
635 if (!!this.people[data.from]) {
636 this.people[data.from].pages
637 .find(p => p.path == data.page).focus = true;
638 this.$forceUpdate(); //TODO: shouldn't be required
642 if (!!this.people[data.from]) {
643 this.people[data.from].pages
644 .find(p => p.path == data.page).focus = false;
645 this.$forceUpdate(); //TODO: shouldn't be required
649 // I logged in elsewhere:
651 alert(this.st.tr["New connexion detected: tab now offline"]);
653 case "askidentity": {
654 // Request for identification (TODO: anonymous shouldn't need to reply)
656 // Decompose to avoid revealing email
657 name: this.st.user.name,
658 sid: this.st.user.sid,
661 this.send("identity", { data: me, target: data.from });
665 const user = data.data;
666 let player = this.people[user.sid];
667 // player.pages is already set
669 player.name = user.name;
670 // TODO: this.$set(people, ...) fails. So forceUpdate.
671 // But this shouldn't be like that!
673 // If I multi-connect, kill current connexion if no mark (I'm older)
674 if (this.newConnect[user.sid]) {
677 user.id == this.st.user.id &&
678 user.sid != this.st.user.sid &&
679 !this.killed[this.st.user.sid]
681 this.send("killme", { sid: this.st.user.sid });
682 this.killed[this.st.user.sid] = true;
684 delete this.newConnect[user.sid];
688 case "askchallenges": {
689 // Send my current live challenges (if any)
690 const myChallenges = this.challenges
692 c.from.sid == this.st.user.sid && c.type == "live"
695 // NOTE: in principle, should only send targeted challenge to the target.
696 // But we may not know yet the identity of the target (just name),
697 // so cannot decide if data.from is the target or not.
700 from: this.st.user.sid,
702 randomness: c.randomness,
709 if (myChallenges.length > 0)
710 this.send("challenges", { data: myChallenges, target: data.from });
713 case "challenges": //after "askchallenges"
714 data.data.forEach(this.addChallenge);
717 this.addChallenge(data.data);
719 case "refusechallenge": {
720 const cid = data.data;
721 ArrayFun.remove(this.challenges, c => c.id == cid);
722 alert(this.st.tr["Challenge declined"]);
725 case "deletechallenge_s": {
726 // NOTE: the challenge(s) may be already removed
727 const cref = data.data;
728 if (!!cref.cid) ArrayFun.remove(this.challenges, c => c.id == cref.cid);
729 else if (!!cref.sids) {
730 cref.sids.forEach(s => {
733 c => c.type == "live" && c.from.sid == s,
740 case "game": //individual request
742 const game = data.data;
743 // Ignore games where I play (will go in MyGames page)
744 if (game.players.every(p =>
745 p.sid != this.st.user.sid || p.uid != this.st.user.id))
747 let locGame = this.games.find(g => g.id == game.id);
750 newGame.type = this.classifyObject(game);
751 newGame.vname = this.getVname(game.vid);
753 // New game from Hall
755 newGame.rids = [game.rid];
756 delete newGame["rid"];
757 this.games.push(newGame);
759 (newGame.type == "live" && this.gdisplay == "corr") ||
760 (newGame.type == "corr" && this.gdisplay == "live")
763 .getElementById("btnG" + newGame.type)
764 .classList.add("somethingnew");
767 // Append rid (if not already in list)
768 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
774 let g = this.games.find(g => g.id == data.gid);
775 if (!!g) g.score = data.score;
779 // New game just started, I'm involved
780 const gameInfo = data.data;
781 if (this.classifyObject(gameInfo) == "live")
782 this.startNewGame(gameInfo);
785 this.st.tr["New correspondance game:"] +
786 " <a href='#/game/" +
792 document.getElementById("modalInfo").checked = true;
797 this.newChat = data.data;
798 if (!document.getElementById("modalPeople").checked)
799 document.getElementById("peopleBtn").classList.add("somethingnew");
803 socketCloseListener: function() {
804 if (!this.conn) return;
805 this.conn = new WebSocket(this.connexionString);
806 this.conn.addEventListener("message", this.socketMessageListener);
807 this.conn.addEventListener("close", this.socketCloseListener);
809 // Challenge lifecycle:
810 addChallenge: function(chall) {
811 // NOTE about next condition: see "askchallenges" case.
814 (this.people[chall.from].id > 0 &&
815 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
817 let newChall = Object.assign({}, chall);
818 newChall.type = this.classifyObject(chall);
819 newChall.randomness = chall.randomness;
820 newChall.added = Date.now();
821 let fromValues = Object.assign({}, this.people[chall.from]);
822 delete fromValues["pages"]; //irrelevant in this context
823 newChall.from = Object.assign({ sid: chall.from }, fromValues);
824 newChall.vname = this.getVname(newChall.vid);
825 this.challenges.push(newChall);
827 (newChall.type == "live" && this.cdisplay == "corr") ||
828 (newChall.type == "corr" && this.cdisplay == "live")
831 .getElementById("btnC" + newChall.type)
832 .classList.add("somethingnew");
836 loadNewchallVariant: async function(cb) {
837 const vname = this.getVname(this.newchallenge.vid);
838 const vModule = await import("@/variants/" + vname + ".js");
839 this.newchallenge.V = vModule.VariantRules;
840 this.newchallenge.vname = vname;
844 trySetNewchallDiag: function() {
845 if (!this.newchallenge.fen) {
846 this.newchallenge.diag = "";
849 // If vid > 0 then the variant is loaded (function above):
850 window.V = this.newchallenge.V;
852 this.newchallenge.vid > 0 &&
853 !!this.newchallenge.fen &&
854 V.IsGoodFen(this.newchallenge.fen)
856 const parsedFen = V.ParseFen(this.newchallenge.fen);
857 this.newchallenge.diag = getDiagram({
858 position: parsedFen.position,
859 orientation: parsedFen.turn
863 newChallFromPreset(pchall) {
864 this.partialResetNewchallenge();
865 this.newchallenge.vid = pchall.vid;
866 this.newchallenge.cadence = pchall.cadence;
867 this.newchallenge.randomness = pchall.randomness;
868 this.issueNewChallenge();
870 issueNewChallenge: async function() {
871 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
872 this.newchallenge.cadence += "+0"; //assume minutes, no increment
873 const ctype = this.classifyObject(this.newchallenge);
874 // TODO: cadence still unchecked so ctype could be wrong...
876 if (!this.newchallenge.vid)
877 error = this.st.tr["Please select a variant"];
878 else if (ctype == "corr" && this.st.user.id <= 0)
879 error = this.st.tr["Please log in to play correspondance games"];
880 else if (!!this.newchallenge.to) {
881 if (this.newchallenge.to == this.st.user.name)
882 error = this.st.tr["Self-challenge is forbidden"];
885 Object.values(this.people).every(p => p.name != this.newchallenge.to)
887 error = this.newchallenge.to + " " + this.st.tr["is not online"];
893 window.V = this.newchallenge.V;
894 error = checkChallenge(this.newchallenge);
899 // NOTE: "from" information is not required here
900 let chall = Object.assign({}, this.newchallenge);
901 // Add only if not already issued (not counting target or FEN):
902 if (this.challenges.some(c =>
903 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
904 c.vid == chall.vid &&
905 c.cadence == chall.cadence &&
906 c.randomness == chall.randomness
908 alert(this.st.tr["Challenge already exists"]);
911 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
913 delete chall["diag"];
914 const finishAddChallenge = cid => {
915 chall.id = cid || "c" + getRandString();
916 const MAX_ALLOWED_CHALLS = 3;
917 // Remove oldest challenge if 3 found: only 3 at a time of a given type
918 let countMyChalls = 0;
919 let challToDelIdx = 0;
920 let oldestAdded = Number.MAX_SAFE_INTEGER;
921 for (let i=0; i<this.challenges.length; i++) {
922 const c = this.challenges[i];
925 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
928 if (c.added < oldestAdded) {
930 oldestAdded = c.added;
934 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
937 { data: { cid: this.challenges[challToDelIdx].id } }
939 if (ctype == "corr") {
943 { data: { id: this.challenges[challToDelIdx].id } }
946 this.challenges.splice(challToDelIdx, 1);
948 this.send("newchallenge", {
949 data: Object.assign({ from: this.st.user.sid }, chall)
951 // Add new challenge:
953 // Decompose to avoid revealing email
954 sid: this.st.user.sid,
956 name: this.st.user.name
958 chall.added = Date.now();
959 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
961 chall.vname = this.newchallenge.vname;
962 this.challenges.push(chall);
963 // Remember cadence + vid for quicker further challenges:
964 localStorage.setItem("cadence", chall.cadence);
965 localStorage.setItem("vid", chall.vid);
966 localStorage.setItem("randomness", chall.randomness);
967 document.getElementById("modalNewgame").checked = false;
968 // Show the challenge if not on current display
970 (ctype == "live" && this.cdisplay == "corr") ||
971 (ctype == "corr" && this.cdisplay == "live")
973 this.setDisplay('c', ctype);
976 if (ctype == "live") {
977 // Live challenges have a random ID
978 finishAddChallenge(null);
980 // Correspondance game: send challenge to server
985 data: { chall: chall },
986 success: (response) => {
987 finishAddChallenge(response.cid);
993 // Callback function after a diagram was showed to accept
994 // or refuse targetted challenge:
995 decisionChallenge: function(accepted) {
996 this.curChallToAccept.accepted = accepted;
997 this.finishProcessingChallenge(this.curChallToAccept);
998 document.getElementById("modalAccept").checked = false;
1000 finishProcessingChallenge: function(c) {
1003 // Again, avoid c.seat = st.user to not reveal email
1004 sid: this.st.user.sid,
1005 id: this.st.user.id,
1006 name: this.st.user.name
1009 if (c.type == "live")
1010 // Remove all live challenges of both players
1011 this.send("deletechallenge_s", { data: { sids: [c.from.sid, c.seat.sid] } });
1013 // Corr challenge: just remove the challenge
1014 this.send("deletechallenge_s", { data: { cid: c.id } });
1016 const oppsid = this.getOppsid(c);
1018 this.send("refusechallenge", { data: c.id, target: oppsid });
1019 if (c.type == "corr") {
1023 { data: { id: c.id } }
1026 this.send("deletechallenge_s", { data: { cid: c.id } });
1029 // TODO: if several players click same challenge at the same time: problem
1030 clickChallenge: async function(c) {
1032 c.from.sid == this.st.user.sid || //live
1033 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1035 if (c.type == "corr" && this.st.user.id <= 0) {
1036 alert(this.st.tr["Please log in to accept corr challenges"]);
1040 const vModule = await import("@/variants/" + c.vname + ".js");
1041 window.V = vModule.VariantRules;
1043 // c.to == this.st.user.name (connected)
1045 const parsedFen = V.ParseFen(c.fen);
1046 c.mycolor = V.GetOppCol(parsedFen.turn);
1047 this.tchallDiag = getDiagram({
1048 position: parsedFen.position,
1049 orientation: c.mycolor
1052 this.curChallToAccept = c;
1053 document.getElementById("modalAccept").checked = true;
1055 else this.finishProcessingChallenge(c);
1059 if (c.type == "corr") {
1063 { data: { id: c.id } }
1066 this.send("deletechallenge_s", { data: { cid: c.id } });
1068 // In all cases, the challenge is consumed:
1069 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1071 // NOTE: when launching game, the challenge is already being deleted
1072 launchGame: function(c) {
1075 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1076 : shuffle([c.from, c.seat]);
1077 // Convention for players IDs in stored games is 'uid'
1078 players.forEach(p => {
1080 pWithUid["uid"] = p.id;
1081 delete pWithUid["id"];
1083 // These game informations will be shared
1085 id: getRandString(),
1086 fen: c.fen || V.GenRandInitFen(c.randomness),
1087 // White player index 0, black player index 1:
1089 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1090 : shuffle([c.from, c.seat]),
1094 const notifyNewgame = () => {
1095 const oppsid = this.getOppsid(c);
1097 // Opponent is online
1098 this.send("startgame", { data: gameInfo, target: oppsid });
1099 // Send game info (only if live) to everyone except me and opponent
1100 // TODO: this double message send could be avoided.
1101 this.send("newgame", { data: gameInfo, oppsid: oppsid });
1102 // Also to MyGames page:
1107 targets: gameInfo.players.map(p => {
1108 return { sid: p.sid, uid: p.uid };
1113 if (c.type == "live") {
1115 this.startNewGame(gameInfo);
1117 // corr: game only on server
1122 // cid is useful to delete the challenge:
1123 data: { gameInfo: gameInfo, cid: c.id },
1124 success: (response) => {
1125 gameInfo.id = response.gameId;
1127 this.$router.push("/game/" + response.gameId);
1133 // NOTE: for live games only (corr games start on the server)
1134 startNewGame: function(gameInfo) {
1135 const game = Object.assign(
1139 // (other) Game infos: constant
1140 fenStart: gameInfo.fen,
1141 vname: this.getVname(gameInfo.vid),
1142 created: Date.now(),
1143 // Game state (including FEN): will be updated
1145 clocks: [-1, -1], //-1 = unstarted
1146 initime: [0, 0], //initialized later
1152 GameStorage.add(game, (err) => {
1153 // If an error occurred, game is not added: a tab already
1154 // added the game and (if focused) is redirected toward it.
1155 // If no error and the tab is hidden: do not show anything.
1156 if (!err && !document.hidden) {
1157 if (this.st.settings.sound)
1158 new Audio("/sounds/newgame.flac").play().catch(() => {});
1159 this.$router.push("/game/" + gameInfo.id);
1163 document.hidden ? 500 + 1000 * Math.random() : 0
1170 <style lang="sass" scoped>
1178 #newgameDiv > .card, #acceptDiv > .card
1182 div#peopleWrap > .card
1185 @media screen and (min-width: 1281px)
1186 div#peopleWrap > .card
1189 @media screen and (max-width: 1280px)
1190 div#peopleWrap > .card
1193 @media screen and (max-width: 767px)
1194 div#peopleWrap > .card
1207 @media screen and (max-width: 767px)
1222 button.player-action
1226 background-color: #c5fefe !important
1229 background-color: #f9faee
1232 background-color: lightgreen
1234 background-color: red
1237 // margin-top set dynamically (depends if diagram showed or not)
1248 // width: 100% required for Firefox
1256 @media screen and (max-width: 767px)
1262 background-color: #FF5733
1264 background-color: #2B63B4
1266 background-color: #33B42B
1269 background-color: lightgrey