3 input#modalInfo.modal(type="checkbox")
6 data-checkbox="modalInfo"
9 label.modal-close(for="modalInfo")
10 p(v-html="infoMessage")
11 input#modalAccept.modal(type="checkbox")
12 div#acceptDiv(role="dialog")
15 span.variantName {{ curChallToAccept.vname }}
16 span {{ curChallToAccept.cadence }}
17 span {{ st.tr["with"] + " " + curChallToAccept.from.name }}
19 v-if="!!curChallToAccept.fen"
22 .button-group#buttonsTchall(:style="tchallButtonsMargin()")
23 button.acceptBtn(@click="decisionChallenge(true)")
24 span {{ st.tr["Accept challenge?"] }}
25 button.refuseBtn(@click="decisionChallenge(false)")
26 span {{ st.tr["Refuse"] }}
27 input#modalNewgame.modal(
29 @change="cadenceFocusIfOpened($event)"
33 data-checkbox="modalNewgame"
36 label#closeNewgame.modal-close(for="modalNewgame")
37 div(@keyup.enter="issueNewChallenge()")
39 label(for="selectVariant") {{ st.tr["Variant"] }} *
41 @change="loadNewchallVariant(trySetNewchallDiag)"
42 v-model="newchallenge.vid"
45 v-for="v in st.variants"
47 :selected="newchallenge.vid==v.id"
51 label(for="cadence") {{ st.tr["Cadence"] }} *
52 div#predefinedCadences
53 button(type="button") 15+5
54 button(type="button") 45+30
55 button(type="button") 3d
56 button(type="button") 7d
59 v-model="newchallenge.cadence"
60 placeholder="5+0, 1h+30s, 5d ..."
63 label(for="selectRandomLevel") {{ st.tr["Randomness"] }} *
64 select#selectRandomLevel(v-model="newchallenge.randomness")
65 option(value="0") {{ st.tr["Deterministic"] }}
66 option(value="1") {{ st.tr["Symmetric random"] }}
67 option(value="2") {{ st.tr["Asymmetric random"] }}
69 label(for="memorizeChall") {{ st.tr["Memorize"] }}
72 v-model="newchallenge.memorize"
74 fieldset(v-if="st.user.id > 0")
75 label(for="selectPlayers") {{ st.tr["Play with"] }}
76 select#selectPlayersInList(v-model="newchallenge.to")
79 v-for="p in Object.values(people)"
85 v-model="newchallenge.to"
87 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
90 @input="trySetNewchallDiag()"
92 v-model="newchallenge.fen"
94 .diagram(v-html="newchallenge.diag")
95 button(@click="issueNewChallenge()") {{ st.tr["Send challenge"] }}
96 input#modalPeople.modal(
98 @click="resetSocialColor()"
102 data-checkbox="modalPeople"
105 label.modal-close(for="modalPeople")
109 v-for="sid in Object.keys(people)"
110 v-if="!!people[sid].name"
112 span {{ people[sid].name }}
113 button.player-action(
115 @click="watchGame(sid)"
117 | {{ st.tr["Observe"] }}
118 button.player-action(
119 v-else-if="isFocusedOnHall(sid)"
120 @click="challenge(sid)"
122 | {{ st.tr["Challenge"] }}
123 p.anonymous @nonymous ({{ anonymousCount() }})
127 @mychat="processChat"
132 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
134 button#peopleBtn(onClick="window.doClick('modalPeople')")
135 | {{ st.tr["Who's there?"] }}
136 button(@click="showNewchallengeForm()")
137 | {{ st.tr["New game"] }}
138 .row(v-if="presetChalls.length > 0")
139 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
140 h4.text-center {{ st.tr["Preset challenges"] }}
144 th {{ st.tr["Variant"] }}
145 th {{ st.tr["Cadence"] }}
146 th {{ st.tr["Random?"] }}
150 v-for="pc in presetChalls"
151 @click="newChallFromPreset(pc)"
155 td(:class="getRandomnessClass(pc)")
156 td.remove-preset(@click="removePresetChall($event, pc)")
157 img(src="/images/icons/delete.svg")
159 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
162 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
163 | {{ st.tr["Live challenges"] }}
164 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
165 | {{ st.tr["Correspondance challenges"] }}
167 v-show="cdisplay=='live'"
168 :challenges="filterChallenges('live')"
169 @click-challenge="clickChallenge"
172 v-show="cdisplay=='corr'"
173 :challenges="filterChallenges('corr')"
174 @click-challenge="clickChallenge"
178 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
179 | {{ st.tr["Live games"] }}
180 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
181 | {{ st.tr["Correspondance games"] }}
183 v-show="gdisplay=='live'"
184 :games="filterGames('live')"
186 @show-game="showGame"
188 div(v-show="gdisplay=='corr'")
190 :games="filterGames('corr')"
192 @show-game="showGame"
198 | {{ st.tr["Load more"] }}
202 import { store } from "@/store";
203 import { checkChallenge } from "@/data/challengeCheck";
204 import { ArrayFun } from "@/utils/array";
205 import { ajax } from "@/utils/ajax";
206 import params from "@/parameters";
207 import { getRandString, shuffle } from "@/utils/alea";
208 import { getDiagram } from "@/utils/printDiagram";
209 import Chat from "@/components/Chat.vue";
210 import GameList from "@/components/GameList.vue";
211 import ChallengeList from "@/components/ChallengeList.vue";
212 import { GameStorage } from "@/utils/gameStorage";
213 import { processModalClick } from "@/utils/modalClick";
224 cdisplay: "live", //or corr
226 // timestamp of last showed (oldest) corr game:
227 cursor: Number.MAX_SAFE_INTEGER,
228 // hasMore == TRUE: a priori there could be more games to load
236 vid: parseInt(localStorage.getItem("vid")) || 0,
237 to: "", //name of challenged player (if any)
238 cadence: localStorage.getItem("cadence") || "",
239 randomness: parseInt(localStorage.getItem("challRandomness")) || 2,
240 // VariantRules object, stored to not interfere with
241 // diagrams of targetted challenges:
244 diag: "", //visualizing FEN
245 memorize: false //put settings in localStorage
248 curChallToAccept: {from: {}},
249 presetChalls: JSON.parse(localStorage.getItem("presetChalls") || "[]"),
253 // Related to (killing of) self multi-connects:
259 // st.variants changes only once, at loading from [] to [...]
260 "st.variants": function() {
261 // Set potential challenges and games variant names:
262 this.challenges.concat(this.games).forEach(o => {
263 if (!o.vname) o.vname = this.getVname(o.vid);
265 if (!this.newchallenge.V && this.newchallenge.vid > 0)
266 this.loadNewchallVariant();
269 created: function() {
270 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
271 this.loadNewchallVariant();
272 const my = this.st.user;
279 pages: [{ path: "/", focus: true }]
282 const connectAndPoll = () => {
283 this.send("connect");
284 this.send("pollclientsandgamers");
286 // Initialize connection
287 this.connexionString =
296 // Hall: path is "/" (could be hard-coded as well)
297 encodeURIComponent(this.$route.path);
298 this.conn = new WebSocket(this.connexionString);
299 this.conn.onopen = connectAndPoll;
300 this.conn.onmessage = this.socketMessageListener;
301 this.conn.onclose = this.socketCloseListener;
303 mounted: function() {
304 document.addEventListener('visibilitychange', this.visibilityChange);
305 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
306 document.getElementById(eltName)
307 .addEventListener("click", processModalClick);
309 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
310 b.addEventListener("click", () => {
311 this.newchallenge.cadence = b.innerHTML;
314 const dispCorr = this.$route.query["disp"];
316 dispCorr || localStorage.getItem("type-challenges") || "live";
318 dispCorr || localStorage.getItem("type-games") || "live";
319 this.setDisplay('c', showCtype);
320 this.setDisplay('g', showGtype);
321 // Ask server for current corr games (all but mines)
327 uid: this.st.user.id,
330 success: (response) => {
331 const L = response.games.length;
333 this.cursor = response.games[L - 1].created;
334 if (this.games.length == 0 && this.gdisplay == "live") {
336 .getElementById("btnGcorr")
337 .classList.add("somethingnew");
340 this.games = this.games.concat(
341 response.games.map(g => {
342 const vname = this.getVname(g.vid);
343 return Object.assign(
356 // Also ask for corr challenges (open + sent by/to me)
361 data: { uid: this.st.user.id },
362 success: (response) => {
364 response.challenges.length > 0 &&
365 this.challenges.length == 0 &&
366 this.cdisplay == "live"
369 .getElementById("btnCcorr")
370 .classList.add("somethingnew");
372 // Gather all senders names, and then retrieve full identity:
373 // (TODO [perf]: some might be online...)
375 response.challenges.forEach(c => {
376 if (c.uid != this.st.user.id) names[c.uid] = "";
377 else if (!!c.target && c.target != this.st.user.id)
378 names[c.target] = "";
380 const addChallenges = () => {
381 names[this.st.user.id] = this.st.user.name; //in case of
382 this.challenges = this.challenges.concat(
383 response.challenges.map(c => {
384 const from = { name: names[c.uid], id: c.uid }; //or just name
385 const type = this.classifyObject(c);
386 const vname = this.getVname(c.vid);
387 return Object.assign(
393 to: c.target ? names[c.target] : ""
400 if (Object.keys(names).length > 0) {
405 data: { ids: Object.keys(names).join(",") },
406 success: (response2) => {
407 response2.users.forEach(u => {
408 names[u.id] = u.name;
414 } else addChallenges();
419 beforeDestroy: function() {
420 document.removeEventListener('visibilitychange', this.visibilityChange);
421 this.send("disconnect");
424 getRandomnessClass: function(pc) {
426 ["random-" + pc.randomness]: true
429 anonymousCount: function() {
431 Object.values(this.people).forEach(p => {
432 // Do not cound people who did not send their identity yet:
433 count += (!p.name && p.id === 0) ? 1 : 0;
437 visibilityChange: function() {
438 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
440 document.visibilityState == "visible"
445 partialResetNewchallenge: function() {
446 // Reset potential target and custom FEN:
447 this.newchallenge.to = "";
448 this.newchallenge.fen = "";
449 this.newchallenge.diag = "";
450 this.newchallenge.memorize = false;
452 showNewchallengeForm: function() {
453 this.partialResetNewchallenge();
454 window.doClick("modalNewgame");
456 addPresetChall: function(chall) {
457 // Add only if not already existing:
458 if (this.presetChalls.some(c =>
459 c.vid == chall.vid &&
460 c.cadence == chall.cadence &&
461 c.randomness == chall.randomness
465 const L = this.presetChalls.length;
466 this.presetChalls.push({
469 vname: chall.vname, //redundant, but easier
470 cadence: chall.cadence,
471 randomness: chall.randomness
473 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
475 removePresetChall: function(e, pchall) {
477 const pchallIdx = this.presetChalls.findIndex(pc => pc.index == pchall.index);
478 this.presetChalls.splice(pchallIdx, 1);
479 localStorage.setItem("presetChalls", JSON.stringify(this.presetChalls));
481 tchallButtonsMargin: function() {
482 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
485 cadenceFocusIfOpened: function() {
486 if (event.target.checked)
487 document.getElementById("cadence").focus();
489 send: function(code, obj) {
491 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
494 getVname: function(vid) {
495 const variant = this.st.variants.find(v => v.id == vid);
496 // this.st.variants might be uninitialized (variant == null)
497 return variant ? variant.name : "";
499 filterChallenges: function(type) {
500 return this.challenges.filter(c => c.type == type);
502 filterGames: function(type) {
503 return this.games.filter(g => g.type == type);
505 classifyObject: function(o) {
506 // o: challenge or game
507 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
509 setDisplay: function(letter, type, e) {
510 this[letter + "display"] = type;
511 localStorage.setItem(
512 "type-" + (letter == "c" ? "challenges" : "games"),
517 : document.getElementById("btn" + letter.toUpperCase() + type);
518 elt.classList.add("active");
519 elt.classList.remove("somethingnew"); //in case of
520 if (!!elt.previousElementSibling)
521 elt.previousElementSibling.classList.remove("active");
522 else elt.nextElementSibling.classList.remove("active");
524 isGamer: function(sid) {
525 return this.people[sid].pages
526 .some(p => p.focus && p.path.indexOf("/game/") >= 0);
528 isFocusedOnHall: function(sid) {
530 // This is meant to challenge people, thus the next 2 conditions:
531 this.st.user.id > 0 &&
532 sid != this.st.user.sid &&
533 this.people[sid].pages.some(p => p.path == "/" && p.focus)
536 challenge: function(sid) {
537 this.partialResetNewchallenge();
538 // Available, in Hall
539 this.newchallenge.to = this.people[sid].name;
540 // TODO: also store target sid to not re-search for it
541 document.getElementById("modalPeople").checked = false;
542 window.doClick("modalNewgame");
544 watchGame: function(sid) {
545 // In some game, maybe playing maybe not: show a random one
547 this.people[sid].pages.forEach(p => {
549 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
550 if (!!matchGid) gids.push(matchGid[0]);
553 const gid = gids[Math.floor(Math.random() * gids.length)];
554 const game = this.games.find(g => g.id == gid);
555 if (!!game) this.showGame(game);
556 else this.$router.push("/game/" + gid); //game vs. me
558 showGame: function(g) {
559 // NOTE: we are an observer, since only games I don't play are shown here
560 // ==> Moves sent by connected remote player(s) if live game
561 this.$router.push("/game/" + g.id);
563 resetSocialColor: function() {
564 // TODO: this is called twice, once on opening an once on closing
565 document.getElementById("peopleBtn").classList.remove("somethingnew");
567 processChat: function(chat) {
568 this.send("newchat", { data: chat });
570 getOppsid: function(c) {
571 let oppsid = c.from.sid; //may not be defined if corr + offline opp
573 oppsid = Object.keys(this.people).find(
574 sid => this.people[sid].id == c.from.id
580 socketMessageListener: function(msg) {
581 if (!this.conn) return;
582 const data = JSON.parse(msg.data);
584 case "pollclientsandgamers": {
585 // Since people can be both in Hall and Game,
586 // need to track "askIdentity" requests:
587 let identityAsked = {};
588 // TODO: shuffling and random filtering on server, if
589 // the room is really crowded.
590 data.sockIds.forEach(s => {
591 const page = s.page || "/";
592 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
593 this.send("askidentity", { target: s.sid, page: page });
594 identityAsked[s.sid] = true;
596 if (!this.people[s.sid]) {
597 // Do not set name or id: identity unknown yet
598 this.people[s.sid] = { pages: [{path: page, focus: true}] };
600 else if (!(this.people[s.sid].pages.find(p => p.path == page)))
601 this.people[s.sid].pages.push({ path: page, focus: true });
604 this.send("askchallenges", { target: s.sid });
605 // Peer is in Game: ask only if live game
606 else if (!page.match(/\/[0-9]+$/))
607 this.send("askgame", { target: s.sid, page: page });
613 const page = data.page || "/";
614 if (data.code == "connect") {
615 // Ask challenges only on first connexion:
616 if (!this.people[data.from])
617 this.send("askchallenges", { target: data.from });
619 // Ask game only if live:
620 else if (!page.match(/\/[0-9]+$/))
621 this.send("askgame", { target: data.from, page: page });
622 if (!this.people[data.from])
623 this.people[data.from] = { pages: [{ path: page, focus: true }] };
625 // Append page if not already in list
626 if (!(this.people[data.from].pages.find(p => p.path == page)))
627 this.people[data.from].pages.push({ path: page, focus: true });
629 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
630 // Identity not known yet
631 this.newConnect[data.from] = true; //for self multi-connects tests
632 this.send("askidentity", { target: data.from, page: page });
637 case "gdisconnect": {
638 // If the user reloads the page twice very quickly (experienced with Firefox),
639 // the first reload won't have time to connect but will trigger a "close" event anyway.
640 // ==> Next check is required.
641 if (!this.people[data.from]) return;
642 const page = data.page || "/";
643 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
644 if (this.people[data.from].pages.length == 0)
645 this.$delete(this.people, data.from);
646 // Disconnect means no more tmpIds:
647 if (data.code == "disconnect") {
648 // Remove the live challenges sent by this player:
651 c => c.type == "live" && c.from.sid == data.from,
655 // Remove the matching live game if now unreachable
656 const gid = page.match(/[a-zA-Z0-9]+$/)[0];
657 // Corr games are always reachable:
658 if (!gid.match(/^[0-9]+$/)) {
659 // Live games are reachable as long as someone is on the game page
660 if (Object.values(this.people).every(p =>
661 p.pages.every(pg => pg.path != page))) {
662 ArrayFun.remove(this.games, g => g.id == gid);
669 // If user reload a page, focus may arrive earlier than connect
670 if (!!this.people[data.from]) {
671 this.people[data.from].pages
672 .find(p => p.path == data.page).focus = true;
673 this.$forceUpdate(); //TODO: shouldn't be required
677 if (!!this.people[data.from]) {
678 this.people[data.from].pages
679 .find(p => p.path == data.page).focus = false;
680 this.$forceUpdate(); //TODO: shouldn't be required
684 // I logged in elsewhere:
686 alert(this.st.tr["New connexion detected: tab now offline"]);
688 case "askidentity": {
689 // Request for identification
691 // Decompose to avoid revealing email
692 name: this.st.user.name,
693 sid: this.st.user.sid,
696 this.send("identity", { data: me, target: data.from });
700 const user = data.data;
701 let player = this.people[user.sid];
702 // player.pages is already set
704 player.name = user.name;
705 // TODO: this.$set(people, ...) fails. So forceUpdate.
706 // But this shouldn't be like that!
708 // If I multi-connect, kill current connexion if no mark (I'm older)
709 if (this.newConnect[user.sid]) {
712 user.id == this.st.user.id &&
713 user.sid != this.st.user.sid &&
714 !this.killed[this.st.user.sid]
716 this.send("killme", { sid: this.st.user.sid });
717 this.killed[this.st.user.sid] = true;
719 delete this.newConnect[user.sid];
723 case "askchallenges": {
724 // Send my current live challenges (if any)
725 const myChallenges = this.challenges
727 c.from.sid == this.st.user.sid && c.type == "live"
730 // NOTE: in principle, should only send targeted challenge to the target.
731 // But we may not know yet the identity of the target (just name),
732 // so cannot decide if data.from is the target or not.
735 from: this.st.user.sid,
737 randomness: c.randomness,
744 if (myChallenges.length > 0)
745 this.send("challenges", { data: myChallenges, target: data.from });
748 case "challenges": //after "askchallenges"
749 data.data.forEach(this.addChallenge);
752 this.addChallenge(data.data);
754 case "refusechallenge": {
755 const cid = data.data;
756 ArrayFun.remove(this.challenges, c => c.id == cid);
757 alert(this.st.tr["Challenge declined"]);
760 case "deletechallenge_s": {
761 // NOTE: the challenge(s) may be already removed
762 const cref = data.data;
763 if (!!cref.cid) ArrayFun.remove(this.challenges, c => c.id == cref.cid);
764 else if (!!cref.sids) {
765 cref.sids.forEach(s => {
768 c => c.type == "live" && c.from.sid == s,
775 case "game": // Individual request
777 const game = data.data;
778 // Ignore games where I play (will go in MyGames page),
779 // and also games that I already received.
781 game.players.every(p =>
782 p.sid != this.st.user.sid && p.id != this.st.user.id) &&
783 this.games.findIndex(g => g.id == game.id) == -1
786 newGame.type = this.classifyObject(game);
787 newGame.vname = this.getVname(game.vid);
789 // New game from Hall
791 this.games.push(newGame);
793 (newGame.type == "live" && this.gdisplay == "corr") ||
794 (newGame.type == "corr" && this.gdisplay == "live")
797 .getElementById("btnG" + newGame.type)
798 .classList.add("somethingnew");
804 let g = this.games.find(g => g.id == data.gid);
805 if (!!g) g.score = data.score;
809 // New game just started, I'm involved
810 const gameInfo = data.data;
811 if (this.classifyObject(gameInfo) == "live")
812 this.startNewGame(gameInfo);
815 this.st.tr["New correspondance game:"] +
816 " <a href='#/game/" +
822 document.getElementById("modalInfo").checked = true;
827 this.newChat = data.data;
828 if (!document.getElementById("modalPeople").checked)
829 document.getElementById("peopleBtn").classList.add("somethingnew");
833 socketCloseListener: function() {
834 if (!this.conn) return;
835 this.conn = new WebSocket(this.connexionString);
836 this.conn.addEventListener("message", this.socketMessageListener);
837 this.conn.addEventListener("close", this.socketCloseListener);
839 loadMore: function() {
845 uid: this.st.user.id,
849 const L = res.games.length;
851 this.cursor = res.games[L - 1].created;
852 let moreGames = res.games.map(g => {
853 const vname = this.getVname(g.vid);
854 return Object.assign(
863 this.games = this.games.concat(moreGames);
864 } else this.hasMore = false;
869 // Challenge lifecycle:
870 addChallenge: function(chall) {
871 // NOTE about next condition: see "askchallenges" case.
874 (this.people[chall.from].id > 0 &&
875 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
877 let newChall = Object.assign({}, chall);
878 newChall.type = this.classifyObject(chall);
879 newChall.randomness = chall.randomness;
880 newChall.added = Date.now();
881 let fromValues = Object.assign({}, this.people[chall.from]);
882 delete fromValues["pages"]; //irrelevant in this context
883 newChall.from = Object.assign({ sid: chall.from }, fromValues);
884 newChall.vname = this.getVname(newChall.vid);
885 this.challenges.push(newChall);
887 (newChall.type == "live" && this.cdisplay == "corr") ||
888 (newChall.type == "corr" && this.cdisplay == "live")
891 .getElementById("btnC" + newChall.type)
892 .classList.add("somethingnew");
896 loadNewchallVariant: async function(cb) {
897 const vname = this.getVname(this.newchallenge.vid);
898 await import("@/variants/" + vname + ".js")
900 window.V = vModule[vname + "Rules"];
901 this.newchallenge.V = window.V;
902 this.newchallenge.vname = vname;
906 trySetNewchallDiag: function() {
907 if (!this.newchallenge.fen) {
908 this.newchallenge.diag = "";
911 // If vid > 0 then the variant is loaded (function above):
912 window.V = this.newchallenge.V;
914 this.newchallenge.vid > 0 &&
915 !!this.newchallenge.fen &&
916 V.IsGoodFen(this.newchallenge.fen)
918 const parsedFen = V.ParseFen(this.newchallenge.fen);
919 this.newchallenge.diag = getDiagram({
920 position: parsedFen.position,
921 orientation: parsedFen.turn
925 newChallFromPreset(pchall) {
926 this.partialResetNewchallenge();
927 this.newchallenge.vid = pchall.vid;
928 this.newchallenge.cadence = pchall.cadence;
929 this.newchallenge.randomness = pchall.randomness;
930 this.loadNewchallVariant(this.issueNewChallenge);
932 issueNewChallenge: async function() {
933 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
934 this.newchallenge.cadence += "+0"; //assume minutes, no increment
935 const ctype = this.classifyObject(this.newchallenge);
936 // TODO: cadence still unchecked so ctype could be wrong...
938 if (!this.newchallenge.vid)
939 error = this.st.tr["Please select a variant"];
940 else if (ctype == "corr" && this.st.user.id <= 0)
941 error = this.st.tr["Please log in to play correspondance games"];
942 else if (!!this.newchallenge.to) {
943 if (this.newchallenge.to == this.st.user.name)
944 error = this.st.tr["Self-challenge is forbidden"];
947 Object.values(this.people).every(p => p.name != this.newchallenge.to)
949 error = this.newchallenge.to + " " + this.st.tr["is not online"];
956 window.V = this.newchallenge.V;
957 error = checkChallenge(this.newchallenge);
962 // NOTE: "from" information is not required here
963 let chall = Object.assign({}, this.newchallenge);
964 // Add only if not already issued (not counting target or FEN):
965 if (this.challenges.some(c =>
966 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
967 c.vid == chall.vid &&
968 c.cadence == chall.cadence &&
969 c.randomness == chall.randomness
971 alert(this.st.tr["Challenge already exists"]);
974 if (this.newchallenge.memorize) this.addPresetChall(this.newchallenge);
976 delete chall["diag"];
977 const finishAddChallenge = cid => {
978 chall.id = cid || "c" + getRandString();
979 const MAX_ALLOWED_CHALLS = 3;
980 // Remove oldest challenge if 3 found: only 3 at a time of a given type
981 let countMyChalls = 0;
982 let challToDelIdx = 0;
983 let oldestAdded = Number.MAX_SAFE_INTEGER;
984 for (let i=0; i<this.challenges.length; i++) {
985 const c = this.challenges[i];
988 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id)
991 if (c.added < oldestAdded) {
993 oldestAdded = c.added;
997 if (countMyChalls >= MAX_ALLOWED_CHALLS) {
1000 { data: { cid: this.challenges[challToDelIdx].id } }
1002 if (ctype == "corr") {
1006 { data: { id: this.challenges[challToDelIdx].id } }
1009 this.challenges.splice(challToDelIdx, 1);
1011 this.send("newchallenge", {
1012 data: Object.assign({ from: this.st.user.sid }, chall)
1014 // Add new challenge:
1016 sid: this.st.user.sid,
1017 id: this.st.user.id,
1018 name: this.st.user.name
1020 chall.added = Date.now();
1021 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
1023 chall.vname = this.newchallenge.vname;
1024 this.challenges.push(chall);
1025 // Remember cadence + vid for quicker further challenges:
1026 localStorage.setItem("cadence", chall.cadence);
1027 localStorage.setItem("vid", chall.vid);
1028 localStorage.setItem("challRandomness", chall.randomness);
1029 document.getElementById("modalNewgame").checked = false;
1030 // Show the challenge if not on current display
1032 (ctype == "live" && this.cdisplay == "corr") ||
1033 (ctype == "corr" && this.cdisplay == "live")
1035 this.setDisplay('c', ctype);
1038 if (ctype == "live") {
1039 // Live challenges have a random ID
1040 finishAddChallenge(null);
1042 // Correspondance game: send challenge to server
1047 data: { chall: chall },
1048 success: (response) => {
1049 finishAddChallenge(response.id);
1055 // Callback function after a diagram was showed to accept
1056 // or refuse targetted challenge:
1057 decisionChallenge: function(accepted) {
1058 this.curChallToAccept.accepted = accepted;
1059 this.finishProcessingChallenge(this.curChallToAccept);
1060 document.getElementById("modalAccept").checked = false;
1062 finishProcessingChallenge: function(c) {
1065 sid: this.st.user.sid,
1066 id: this.st.user.id,
1067 name: this.st.user.name
1070 if (c.type == "live")
1071 // Remove all live challenges of both players
1072 this.send("deletechallenge_s", { data: { sids: [c.from.sid, c.seat.sid] } });
1074 // Corr challenge: just remove the challenge
1075 this.send("deletechallenge_s", { data: { cid: c.id } });
1077 const oppsid = this.getOppsid(c);
1079 this.send("refusechallenge", { data: c.id, target: oppsid });
1080 if (c.type == "corr") {
1084 { data: { id: c.id } }
1087 this.send("deletechallenge_s", { data: { cid: c.id } });
1090 // TODO: if several players click same challenge at the same time: problem
1091 clickChallenge: async function(c) {
1093 c.from.sid == this.st.user.sid || //live
1094 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
1096 if (c.type == "corr" && this.st.user.id <= 0) {
1097 alert(this.st.tr["Please log in to accept corr challenges"]);
1101 await import("@/variants/" + c.vname + ".js")
1102 .then((vModule) => {
1103 window.V = vModule[c.vname + "Rules"];
1105 // c.to == this.st.user.name (connected)
1107 const parsedFen = V.ParseFen(c.fen);
1108 c.mycolor = V.GetOppCol(parsedFen.turn);
1109 this.tchallDiag = getDiagram({
1110 position: parsedFen.position,
1111 orientation: c.mycolor
1114 this.curChallToAccept = c;
1115 document.getElementById("modalAccept").checked = true;
1117 else this.finishProcessingChallenge(c);
1122 if (c.type == "corr") {
1126 { data: { id: c.id } }
1129 this.send("deletechallenge_s", { data: { cid: c.id } });
1131 // In all cases, the challenge is consumed:
1132 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
1134 // NOTE: when launching game, the challenge is already being deleted
1135 launchGame: function(c) {
1136 // White player index 0, black player index 1:
1139 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
1140 : shuffle([c.from, c.seat]);
1141 // These game informations will be shared
1143 id: getRandString(),
1144 fen: c.fen || V.GenRandInitFen(c.randomness),
1145 randomness: c.randomness, //for rematch
1150 const notifyNewgame = () => {
1151 const oppsid = this.getOppsid(c);
1153 // Opponent is online
1154 this.send("startgame", { data: gameInfo, target: oppsid });
1155 // If new corr game, notify Hall (except opponent and me)
1156 if (c.type == "corr") {
1161 excluded: [this.st.user.sid, oppsid]
1165 // Notify MyGames page:
1170 targets: gameInfo.players
1173 // NOTE: no need to send the game to the room, since I'll connect
1174 // on game just after, the main Hall will be notified.
1176 if (c.type == "live") {
1178 this.startNewGame(gameInfo);
1180 // corr: game only on server
1185 // cid is useful to delete the challenge:
1190 success: (response) => {
1191 gameInfo.id = response.id;
1193 this.$router.push("/game/" + response.id);
1199 // NOTE: for live games only (corr games start on the server)
1200 startNewGame: function(gameInfo) {
1201 const game = Object.assign(
1205 // (other) Game infos: constant
1206 fenStart: gameInfo.fen,
1207 vname: this.getVname(gameInfo.vid),
1208 created: Date.now(),
1209 // Game state (including FEN): will be updated
1211 clocks: [-1, -1], //-1 = unstarted
1212 initime: [0, 0], //initialized later
1218 GameStorage.add(game, (err) => {
1219 // If an error occurred, game is not added: a tab already
1220 // added the game. Maybe a focused one, maybe not.
1221 // We know for sure that it emitted the gong start sound.
1222 // ==> Do not play it again.
1223 if (!err && this.st.settings.sound)
1224 new Audio("/sounds/newgame.flac").play().catch(() => {});
1225 this.$router.push("/game/" + gameInfo.id);
1228 document.hidden ? 500 + 1000 * Math.random() : 0
1235 <style lang="sass" scoped>
1243 #newgameDiv > .card, #acceptDiv > .card
1247 div#peopleWrap > .card
1250 @media screen and (min-width: 1281px)
1251 div#peopleWrap > .card
1254 @media screen and (max-width: 1280px)
1255 div#peopleWrap > .card
1258 @media screen and (max-width: 767px)
1259 div#peopleWrap > .card
1272 @media screen and (max-width: 767px)
1287 button.player-action
1291 background-color: #c5fefe !important
1294 background-color: #f9faee
1297 background-color: lightgreen
1299 background-color: red
1302 // margin-top set dynamically (depends if diagram showed or not)
1313 // width: 100% required for Firefox
1321 @media screen and (max-width: 767px)
1327 background-color: #FF5733
1329 background-color: #2B63B4
1331 background-color: #33B42B
1333 @media screen and (max-width: 767px)
1342 background-color: lightgrey