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="newChallenge()")
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"] }}
68 fieldset(v-if="st.user.id > 0")
69 label(for="selectPlayers") {{ st.tr["Play with?"] }}
72 v-model="newchallenge.to"
74 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
77 @input="trySetNewchallDiag()"
79 v-model="newchallenge.fen"
81 .diagram(v-html="newchallenge.diag")
82 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
83 input#modalPeople.modal(
85 @click="resetSocialColor()"
89 data-checkbox="modalPeople"
92 label.modal-close(for="modalPeople")
96 v-for="sid in Object.keys(people)"
97 v-if="!!people[sid].name"
99 span {{ people[sid].name }}
100 button.player-action(
102 @click="watchGame(sid)"
104 | {{ st.tr["Observe"] }}
105 button.player-action(
106 v-else-if="isFocusedOnHall(sid)"
107 @click="challenge(sid)"
109 | {{ st.tr["Challenge"] }}
110 p.anonymous @nonymous ({{ anonymousCount }})
114 @mychat="processChat"
119 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
121 button#peopleBtn(onClick="window.doClick('modalPeople')")
122 | {{ st.tr["Who's there?"] }}
123 button(@click="showNewchallengeForm()")
124 | {{ st.tr["New game"] }}
126 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
129 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
130 | {{ st.tr["Live challenges"] }}
131 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
132 | {{ st.tr["Correspondance challenges"] }}
134 v-show="cdisplay=='live'"
135 :challenges="filterChallenges('live')"
136 @click-challenge="clickChallenge"
139 v-show="cdisplay=='corr'"
140 :challenges="filterChallenges('corr')"
141 @click-challenge="clickChallenge"
145 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
146 | {{ st.tr["Live games"] }}
147 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
148 | {{ st.tr["Correspondance games"] }}
150 v-show="gdisplay=='live'"
151 :games="filterGames('live')"
153 @show-game="showGame"
156 v-show="gdisplay=='corr'"
157 :games="filterGames('corr')"
159 @show-game="showGame"
164 import { store } from "@/store";
165 import { checkChallenge } from "@/data/challengeCheck";
166 import { ArrayFun } from "@/utils/array";
167 import { ajax } from "@/utils/ajax";
168 import params from "@/parameters";
169 import { getRandString, shuffle } from "@/utils/alea";
170 import { getDiagram } from "@/utils/printDiagram";
171 import Chat from "@/components/Chat.vue";
172 import GameList from "@/components/GameList.vue";
173 import ChallengeList from "@/components/ChallengeList.vue";
174 import { GameStorage } from "@/utils/gameStorage";
175 import { processModalClick } from "@/utils/modalClick";
186 cdisplay: "live", //or corr
194 vid: parseInt(localStorage.getItem("vid")) || 0,
195 to: "", //name of challenged player (if any)
196 cadence: localStorage.getItem("cadence") || "",
197 randomness: parseInt(localStorage.getItem("randomness")) || 2,
198 // VariantRules object, stored to not interfere with
199 // diagrams of targetted challenges:
202 diag: "" //visualizing FEN
205 curChallToAccept: {from: {}},
209 // Related to (killing of) self multi-connects:
215 // st.variants changes only once, at loading from [] to [...]
216 "st.variants": function() {
217 // Set potential challenges and games variant names:
218 this.challenges.concat(this.games).forEach(o => {
219 if (!o.vname) o.vname = this.getVname(o.vid);
221 if (!this.newchallenge.V && this.newchallenge.vid > 0)
222 this.loadNewchallVariant();
226 anonymousCount: function() {
228 Object.values(this.people).forEach(p => {
229 // Do not cound people who did not send their identity yet:
230 count += (!p.name && p.id === 0) ? 1 : 0;
235 created: function() {
236 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
237 this.loadNewchallVariant();
238 const my = this.st.user;
245 pages: [{ path: "/", focus: true }]
248 // Ask server for current corr games (all but mines)
253 data: { uid: this.st.user.id, excluded: true },
254 success: (response) => {
255 this.games = this.games.concat(
256 response.games.map(g => {
257 const type = this.classifyObject(g);
258 const vname = this.getVname(g.vid);
259 return Object.assign({}, g, { type: type, vname: vname });
265 // Also ask for corr challenges (open + sent by/to me)
270 data: { uid: this.st.user.id },
271 success: (response) => {
272 // Gather all senders names, and then retrieve full identity:
273 // (TODO [perf]: some might be online...)
275 response.challenges.forEach(c => {
276 if (c.uid != this.st.user.id) names[c.uid] = "";
277 else if (!!c.target && c.target != this.st.user.id)
278 names[c.target] = "";
280 const addChallenges = () => {
281 names[this.st.user.id] = this.st.user.name; //in case of
282 this.challenges = this.challenges.concat(
283 response.challenges.map(c => {
284 const from = { name: names[c.uid], id: c.uid }; //or just name
285 const type = this.classifyObject(c);
286 const vname = this.getVname(c.vid);
287 return Object.assign(
293 to: c.target ? names[c.target] : ""
300 if (Object.keys(names).length > 0) {
305 data: { ids: Object.keys(names).join(",") },
306 success: (response2) => {
307 response2.users.forEach(u => {
308 names[u.id] = u.name;
314 } else addChallenges();
318 const connectAndPoll = () => {
319 this.send("connect");
320 this.send("pollclientsandgamers");
322 // Initialize connection
323 this.connexionString =
332 // Hall: path is "/" (could be hard-coded as well)
333 encodeURIComponent(this.$route.path);
334 this.conn = new WebSocket(this.connexionString);
335 this.conn.onopen = connectAndPoll;
336 this.conn.onmessage = this.socketMessageListener;
337 this.conn.onclose = this.socketCloseListener;
339 mounted: function() {
340 document.addEventListener('visibilitychange', this.visibilityChange);
341 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
342 let elt = document.getElementById(eltName);
343 elt.addEventListener("click", processModalClick);
345 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
346 b.addEventListener("click", () => {
347 this.newchallenge.cadence = b.innerHTML;
350 const dispCorr = this.$route.query["disp"];
352 dispCorr || localStorage.getItem("type-challenges") || "live";
354 dispCorr || localStorage.getItem("type-games") || "live";
355 this.setDisplay("c", showCtype);
356 this.setDisplay("g", showGtype);
358 beforeDestroy: function() {
359 document.removeEventListener('visibilitychange', this.visibilityChange);
360 this.send("disconnect");
363 visibilityChange: function() {
364 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
366 document.visibilityState == "visible"
371 partialResetNewchallenge: function() {
372 // Reset potential target and custom FEN:
373 this.newchallenge.to = "";
374 this.newchallenge.fen = "";
375 this.newchallenge.diag = "";
377 showNewchallengeForm: function() {
378 this.partialResetNewchallenge();
379 window.doClick("modalNewgame");
381 tchallButtonsMargin: function() {
382 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
385 cadenceFocusIfOpened: function() {
386 if (event.target.checked)
387 document.getElementById("cadence").focus();
389 send: function(code, obj) {
391 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
394 getVname: function(vid) {
395 const variant = this.st.variants.find(v => v.id == vid);
396 // this.st.variants might be uninitialized (variant == null)
397 return variant ? variant.name : "";
399 filterChallenges: function(type) {
400 return this.challenges.filter(c => c.type == type);
402 filterGames: function(type) {
403 return this.games.filter(g => g.type == type);
405 classifyObject: function(o) {
407 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
409 setDisplay: function(letter, type, e) {
410 this[letter + "display"] = type;
411 localStorage.setItem(
412 "type-" + (letter == "c" ? "challenges" : "games"),
417 : document.getElementById("btn" + letter.toUpperCase() + type);
418 elt.classList.add("active");
419 elt.classList.remove("somethingnew"); //in case of
420 if (!!elt.previousElementSibling)
421 elt.previousElementSibling.classList.remove("active");
422 else elt.nextElementSibling.classList.remove("active");
424 isGamer: function(sid) {
425 return this.people[sid].pages
426 .some(p => p.focus && p.path.indexOf("/game/") >= 0);
428 isFocusedOnHall: function(sid) {
430 // This is meant to challenge people, thus the next 2 conditions:
431 this.st.user.id > 0 &&
432 sid != this.st.user.sid &&
433 this.people[sid].pages.some(p => p.path == "/" && p.focus)
436 challenge: function(sid) {
437 this.partialResetNewchallenge();
438 // Available, in Hall
439 this.newchallenge.to = this.people[sid].name;
440 document.getElementById("modalPeople").checked = false;
441 window.doClick("modalNewgame");
443 watchGame: function(sid) {
444 // In some game, maybe playing maybe not: show a random one
446 this.people[sid].pages.forEach(p => {
448 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
449 if (!!matchGid) gids.push(matchGid[0]);
452 const gid = gids[Math.floor(Math.random() * gids.length)];
453 const game = this.games.find(g => g.id == gid);
454 if (!!game) this.showGame(game);
455 else this.$router.push("/game/" + gid); //game vs. me
457 showGame: function(g) {
458 // NOTE: we are an observer, since only games I don't play are shown here
459 // ==> Moves sent by connected remote player(s) if live game
460 let url = "/game/" + g.id;
461 if (g.type == "live")
462 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
463 this.$router.push(url);
465 resetSocialColor: function() {
466 // TODO: this is called twice, once on opening an once on closing
467 document.getElementById("peopleBtn").classList.remove("somethingnew");
469 processChat: function(chat) {
470 this.send("newchat", { data: chat });
472 getOppsid: function(c) {
473 let oppsid = c.from.sid; //may not be defined if corr + offline opp
475 oppsid = Object.keys(this.people).find(
476 sid => this.people[sid].id == c.from.id
482 socketMessageListener: function(msg) {
483 if (!this.conn) return;
484 const data = JSON.parse(msg.data);
486 case "pollclientsandgamers": {
487 // Since people can be both in Hall and Game,
488 // need to track "askIdentity" requests:
489 let identityAsked = {};
490 data.sockIds.forEach(s => {
491 const page = s.page || "/";
492 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
493 this.send("askidentity", { target: s.sid, page: page });
494 identityAsked[s.sid] = true;
496 if (!this.people[s.sid]) {
497 // Do not set name or id: identity unknown yet
498 this.people[s.sid] = { pages: [{path: page, focus: true}] };
500 else if (!(this.people[s.sid].pages.find(p => p.path == page)))
501 this.people[s.sid].pages.push({ path: page, focus: true });
504 this.send("askchallenge", { target: s.sid });
506 else this.send("askgame", { target: s.sid, page: page });
512 const page = data.page || "/";
513 // Only ask game / challenge if first connexion:
514 if (!this.people[data.from]) {
515 this.people[data.from] = { pages: [{ path: page, focus: true }] };
516 if (data.code == "connect")
517 this.send("askchallenge", { target: data.from });
518 else this.send("askgame", { target: data.from, page: page });
520 // Append page if not already in list
521 if (!(this.people[data.from].pages.find(p => p.path == page)))
522 this.people[data.from].pages.push({ path: page, focus: true });
524 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
525 // Identity not known yet
526 this.newConnect[data.from] = true; //for self multi-connects tests
527 this.send("askidentity", { target: data.from, page: page });
532 case "gdisconnect": {
533 // If the user reloads the page twice very quickly (experienced with Firefox),
534 // the first reload won't have time to connect but will trigger a "close" event anyway.
535 // ==> Next check is required.
536 if (!this.people[data.from]) return;
537 // Disconnect means no more tmpIds:
538 if (data.code == "disconnect") {
539 // Remove the live challenge sent by this player:
542 c => c.type == "live" && c.from.sid == data.from
545 // Remove the matching live game if now unreachable
546 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
547 const gidx = this.games.findIndex(g => g.id == gid);
549 const game = this.games[gidx];
551 game.type == "live" &&
552 game.rids.length == 1 &&
553 game.rids[0] == data.from
555 this.games.splice(gidx, 1);
559 const page = data.page || "/";
560 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
561 if (this.people[data.from].pages.length == 0)
562 this.$delete(this.people, data.from);
566 // If user reload a page, focus may arrive earlier than connect
567 if (!!this.people[data.from]) {
568 this.people[data.from].pages
569 .find(p => p.path == data.page).focus = true;
570 this.$forceUpdate(); //TODO: shouldn't be required
574 if (!!this.people[data.from]) {
575 this.people[data.from].pages
576 .find(p => p.path == data.page).focus = false;
577 this.$forceUpdate(); //TODO: shouldn't be required
581 // I logged in elsewhere:
583 alert(this.st.tr["New connexion detected: tab now offline"]);
585 case "askidentity": {
586 // Request for identification (TODO: anonymous shouldn't need to reply)
588 // Decompose to avoid revealing email
589 name: this.st.user.name,
590 sid: this.st.user.sid,
593 this.send("identity", { data: me, target: data.from });
597 const user = data.data;
598 let player = this.people[user.sid];
599 // player.pages is already set
601 player.name = user.name;
602 // TODO: this.$set(people, ...) fails. So forceUpdate.
603 // But this shouldn't be like that!
605 // If I multi-connect, kill current connexion if no mark (I'm older)
606 if (this.newConnect[user.sid]) {
609 user.id == this.st.user.id &&
610 user.sid != this.st.user.sid &&
611 !this.killed[this.st.user.sid]
613 this.send("killme", { sid: this.st.user.sid });
614 this.killed[this.st.user.sid] = true;
616 delete this.newConnect[user.sid];
620 case "askchallenge": {
621 // Send my current live challenge (if any)
622 const cIdx = this.challenges.findIndex(
623 c => c.from.sid == this.st.user.sid && c.type == "live"
626 const c = this.challenges[cIdx];
627 // NOTE: in principle, should only send targeted challenge to the target.
628 // But we may not know yet the identity of the target (just name),
629 // so cannot decide if data.from is the target or not.
630 const myChallenge = {
632 from: this.st.user.sid,
634 randomness: c.randomness,
640 this.send("challenge", { data: myChallenge, target: data.from });
644 case "challenge": //after "askchallenge"
645 case "newchallenge": {
646 // NOTE about next condition: see "askchallenge" case.
647 const chall = data.data;
650 (this.people[chall.from].id > 0 &&
651 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
653 let newChall = Object.assign({}, chall);
654 newChall.type = this.classifyObject(chall);
655 newChall.randomness = chall.randomness;
656 newChall.added = Date.now();
657 let fromValues = Object.assign({}, this.people[chall.from]);
658 delete fromValues["pages"]; //irrelevant in this context
659 newChall.from = Object.assign({ sid: chall.from }, fromValues);
660 newChall.vname = this.getVname(newChall.vid);
661 this.challenges.push(newChall);
663 (newChall.type == "live" && this.cdisplay == "corr") ||
664 (newChall.type == "corr" && this.cdisplay == "live")
667 .getElementById("btnC" + newChall.type)
668 .classList.add("somethingnew");
673 case "refusechallenge": {
674 const cid = data.data;
675 ArrayFun.remove(this.challenges, c => c.id == cid);
676 alert(this.st.tr["Challenge declined"]);
679 case "deletechallenge": {
680 // NOTE: the challenge may be already removed
681 const cid = data.data;
682 ArrayFun.remove(this.challenges, c => c.id == cid);
685 case "game": //individual request
687 const game = data.data;
688 // Ignore games where I play (will go in MyGames page)
689 if (game.players.every(p =>
690 p.sid != this.st.user.sid || p.uid != this.st.user.id))
692 let locGame = this.games.find(g => g.id == game.id);
695 newGame.type = this.classifyObject(game);
696 newGame.vname = this.getVname(game.vid);
698 //if new game from Hall
700 newGame.rids = [game.rid];
701 delete newGame["rid"];
702 this.games.push(newGame);
704 (newGame.type == "live" && this.gdisplay == "corr") ||
705 (newGame.type == "corr" && this.gdisplay == "live")
708 .getElementById("btnG" + newGame.type)
709 .classList.add("somethingnew");
712 // Append rid (if not already in list)
713 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
719 let g = this.games.find(g => g.id == data.gid);
720 if (!!g) g.score = data.score;
724 // New game just started, I'm involved
725 const gameInfo = data.data;
726 if (this.classifyObject(gameInfo) == "live")
727 this.startNewGame(gameInfo);
730 this.st.tr["New correspondance game:"] +
731 " <a href='#/game/" +
737 document.getElementById("modalInfo").checked = true;
742 this.newChat = data.data;
743 if (!document.getElementById("modalPeople").checked)
744 document.getElementById("peopleBtn").classList.add("somethingnew");
748 socketCloseListener: function() {
749 if (!this.conn) return;
750 this.conn = new WebSocket(this.connexionString);
751 this.conn.addEventListener("message", this.socketMessageListener);
752 this.conn.addEventListener("close", this.socketCloseListener);
754 // Challenge lifecycle:
755 loadNewchallVariant: async function(cb) {
756 const vname = this.getVname(this.newchallenge.vid);
757 const vModule = await import("@/variants/" + vname + ".js");
758 this.newchallenge.V = vModule.VariantRules;
759 this.newchallenge.vname = vname;
763 trySetNewchallDiag: function() {
764 if (!this.newchallenge.fen) {
765 this.newchallenge.diag = "";
768 // If vid > 0 then the variant is loaded (function above):
769 window.V = this.newchallenge.V;
771 this.newchallenge.vid > 0 &&
772 !!this.newchallenge.fen &&
773 V.IsGoodFen(this.newchallenge.fen)
775 const parsedFen = V.ParseFen(this.newchallenge.fen);
776 this.newchallenge.diag = getDiagram({
777 position: parsedFen.position,
778 orientation: parsedFen.turn
782 newChallenge: async function() {
783 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
784 this.newchallenge.cadence += "+0"; //assume minutes, no increment
785 const ctype = this.classifyObject(this.newchallenge);
786 // TODO: cadence still unchecked so ctype could be wrong...
788 if (!this.newchallenge.vid)
789 error = this.st.tr["Please select a variant"];
790 else if (ctype == "corr" && this.st.user.id <= 0)
791 error = this.st.tr["Please log in to play correspondance games"];
792 else if (!!this.newchallenge.to) {
793 if (this.newchallenge.to == this.st.user.name)
794 error = this.st.tr["Self-challenge is forbidden"];
797 Object.values(this.people).every(p => p.name != this.newchallenge.to)
799 error = this.newchallenge.to + " " + this.st.tr["is not online"];
805 window.V = this.newchallenge.V;
806 error = checkChallenge(this.newchallenge);
811 // NOTE: "from" information is not required here
812 let chall = Object.assign({}, this.newchallenge);
814 delete chall["diag"];
815 const finishAddChallenge = cid => {
816 chall.id = cid || "c" + getRandString();
817 // Remove old challenge if any (only one at a time of a given type):
818 const cIdx = this.challenges.findIndex(
820 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
824 // Delete current challenge (will be replaced now)
825 this.send("deletechallenge", { data: this.challenges[cIdx].id });
826 if (ctype == "corr") {
830 { data: { id: this.challenges[cIdx].id } }
833 this.challenges.splice(cIdx, 1);
835 this.send("newchallenge", {
836 data: Object.assign({ from: this.st.user.sid }, chall)
838 // Add new challenge:
840 // Decompose to avoid revealing email
841 sid: this.st.user.sid,
843 name: this.st.user.name
845 chall.added = Date.now();
846 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
848 chall.vname = this.newchallenge.vname;
849 this.challenges.push(chall);
850 // Remember cadence + vid for quicker further challenges:
851 localStorage.setItem("cadence", chall.cadence);
852 localStorage.setItem("vid", chall.vid);
853 localStorage.setItem("randomness", chall.randomness);
854 document.getElementById("modalNewgame").checked = false;
855 // Show the challenge if not on current display
857 (ctype == "live" && this.cdisplay == "corr") ||
858 (ctype == "corr" && this.cdisplay == "live")
860 this.setDisplay('c', ctype);
863 if (ctype == "live") {
864 // Live challenges have a random ID
865 finishAddChallenge(null);
867 // Correspondance game: send challenge to server
872 data: { chall: chall },
873 success: (response) => {
874 finishAddChallenge(response.cid);
880 // Callback function after a diagram was showed to accept
881 // or refuse targetted challenge:
882 decisionChallenge: function(accepted) {
883 this.curChallToAccept.accepted = accepted;
884 this.finishProcessingChallenge(this.curChallToAccept);
885 document.getElementById("modalAccept").checked = false;
887 finishProcessingChallenge: function(c) {
890 // Again, avoid c.seat = st.user to not reveal email
891 sid: this.st.user.sid,
893 name: this.st.user.name
897 const oppsid = this.getOppsid(c);
899 this.send("refusechallenge", { data: c.id, target: oppsid });
900 if (c.type == "corr") {
904 { data: { id: c.id } }
908 this.send("deletechallenge", { data: c.id });
910 clickChallenge: async function(c) {
912 c.from.sid == this.st.user.sid || //live
913 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
915 if (c.type == "corr" && this.st.user.id <= 0) {
916 alert(this.st.tr["Please log in to accept corr challenges"]);
920 const vModule = await import("@/variants/" + c.vname + ".js");
921 window.V = vModule.VariantRules;
923 // c.to == this.st.user.name (connected)
925 const parsedFen = V.ParseFen(c.fen);
926 c.mycolor = V.GetOppCol(parsedFen.turn);
927 this.tchallDiag = getDiagram({
928 position: parsedFen.position,
929 orientation: c.mycolor
932 this.curChallToAccept = c;
933 document.getElementById("modalAccept").checked = true;
935 else this.finishProcessingChallenge(c);
939 if (c.type == "corr") {
943 { data: { id: c.id } }
946 this.send("deletechallenge", { data: c.id });
948 // In all cases, the challenge is consumed:
949 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
951 // NOTE: when launching game, the challenge is already being deleted
952 launchGame: function(c) {
955 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
956 : shuffle([c.from, c.seat]);
957 // Convention for players IDs in stored games is 'uid'
958 players.forEach(p => {
960 pWithUid["uid"] = p.id;
961 delete pWithUid["id"];
963 // These game informations will be shared
966 fen: c.fen || V.GenRandInitFen(c.randomness),
967 // White player index 0, black player index 1:
969 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
970 : shuffle([c.from, c.seat]),
974 const notifyNewgame = () => {
975 const oppsid = this.getOppsid(c);
977 // Opponent is online
978 this.send("startgame", { data: gameInfo, target: oppsid });
979 // Send game info (only if live) to everyone except me and opponent
980 // TODO: this double message send could be avoided.
981 this.send("newgame", { data: gameInfo, oppsid: oppsid });
982 // Also to MyGames page:
987 targets: gameInfo.players.map(p => {
988 return { sid: p.sid, uid: p.uid };
993 if (c.type == "live") {
995 this.startNewGame(gameInfo);
997 // corr: game only on server
1002 // cid is useful to delete the challenge:
1003 data: { gameInfo: gameInfo, cid: c.id },
1004 success: (response) => {
1005 gameInfo.id = response.gameId;
1007 this.$router.push("/game/" + response.gameId);
1013 // NOTE: for live games only (corr games start on the server)
1014 startNewGame: function(gameInfo) {
1015 const game = Object.assign(
1019 // (other) Game infos: constant
1020 fenStart: gameInfo.fen,
1021 vname: this.getVname(gameInfo.vid),
1022 created: Date.now(),
1023 // Game state (including FEN): will be updated
1025 clocks: [-1, -1], //-1 = unstarted
1026 initime: [0, 0], //initialized later
1032 GameStorage.add(game, (err) => {
1033 // If an error occurred, game is not added: a tab already
1034 // added the game and (if focused) is redirected toward it.
1035 // If no error and the tab is hidden: do not show anything.
1036 if (!err && !document.hidden) {
1037 if (this.st.settings.sound)
1038 new Audio("/sounds/newgame.flac").play().catch(() => {});
1039 this.$router.push("/game/" + gameInfo.id);
1043 document.hidden ? 500 + 1000 * Math.random() : 0
1050 <style lang="sass" scoped>
1058 #newgameDiv > .card, #acceptDiv > .card
1062 div#peopleWrap > .card
1065 @media screen and (min-width: 1281px)
1066 div#peopleWrap > .card
1069 @media screen and (max-width: 1280px)
1070 div#peopleWrap > .card
1073 @media screen and (max-width: 767px)
1074 div#peopleWrap > .card
1087 @media screen and (max-width: 767px)
1102 button.player-action
1106 background-color: #c5fefe !important
1109 background-color: #f9faee
1112 background-color: lightgreen
1114 background-color: red
1117 // margin-top set dynamically (depends if diagram showed or not)
1128 // width: 100% required for Firefox
1136 @media screen and (max-width: 767px)