6f2dfeab9b616c0a04869106e446361f1dcaa9e1
[vchess.git] / client / src / views / Hall.vue
1 <template lang="pug">
2 main
3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(role="dialog" data-checkbox="modalInfo")
5 .card.text-center
6 label.modal-close(for="modalInfo")
7 p(v-html="infoMessage")
8 input#modalNewgame.modal(type="checkbox")
9 div#newgameDiv(role="dialog" data-checkbox="modalNewgame")
10 .card
11 label#closeNewgame.modal-close(for="modalNewgame")
12 form(@submit.prevent="newChallenge()" @keyup.enter="newChallenge()")
13 fieldset
14 label(for="selectVariant") {{ st.tr["Variant"] }} *
15 select#selectVariant(v-model="newchallenge.vid")
16 option(v-for="v in st.variants" :value="v.id"
17 :selected="newchallenge.vid==v.id")
18 | {{ v.name }}
19 fieldset
20 label(for="cadence") {{ st.tr["Cadence"] }} *
21 div#predefinedCadences
22 button 3+2
23 button 5+3
24 button 15+5
25 input#cadence(type="text" v-model="newchallenge.cadence"
26 placeholder="5+0, 1h+30s, 7d+1d ...")
27 fieldset(v-if="st.user.id > 0")
28 label(for="selectPlayers") {{ st.tr["Play with?"] }}
29 input#selectPlayers(type="text" v-model="newchallenge.to")
30 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
31 label(for="inputFen") FEN
32 input#inputFen(type="text" v-model="newchallenge.fen")
33 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
34 input#modalPeople.modal(type="checkbox" @click="resetChatColor()")
35 div#peopleWrap(role="dialog" data-checkbox="modalPeople")
36 .card
37 label.modal-close(for="modalPeople")
38 #people
39 #players
40 p(v-for="sid in Object.keys(people)" v-if="!!people[sid].name")
41 span {{ people[sid].name }}
42 button.player-action(v-if="sid!=st.user.sid || isGamer(sid)" @click="challOrWatch(sid)")
43 | {{ getActionLabel(sid) }}
44 p.anonymous @nonymous ({{ anonymousCount }})
45 #chat
46 Chat(:newChat="newChat" @mychat="processChat" :pastChats="[]")
47 .clearer
48 .row
49 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
50 .button-group
51 button#peopleBtn(onClick="doClick('modalPeople')") {{ st.tr["Social"] }}
52 button(onClick="doClick('modalNewgame')") {{ st.tr["New game"] }}
53 .row
54 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
55 div#div2
56 .button-group
57 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
58 | {{ st.tr["Live challenges"] }}
59 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
60 | {{ st.tr["Correspondance challenges"] }}
61 ChallengeList(v-show="cdisplay=='live'"
62 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
63 ChallengeList(v-show="cdisplay=='corr'"
64 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
65 div#div3
66 .button-group
67 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
68 | {{ st.tr["Live games"] }}
69 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
70 | {{ st.tr["Correspondance games"] }}
71 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
72 :showBoth="true" @show-game="showGame")
73 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
74 :showBoth="true" @show-game="showGame")
75 </template>
76
77 <script>
78 import { store } from "@/store";
79 import { checkChallenge } from "@/data/challengeCheck";
80 import { ArrayFun } from "@/utils/array";
81 import { ajax } from "@/utils/ajax";
82 import params from "@/parameters";
83 import { getRandString, shuffle } from "@/utils/alea";
84 import Chat from "@/components/Chat.vue";
85 import GameList from "@/components/GameList.vue";
86 import ChallengeList from "@/components/ChallengeList.vue";
87 import { GameStorage } from "@/utils/gameStorage";
88 import { processModalClick } from "@/utils/modalClick";
89 export default {
90 name: "my-hall",
91 components: {
92 Chat,
93 GameList,
94 ChallengeList,
95 },
96 data: function () {
97 return {
98 st: store.state,
99 cdisplay: "live", //or corr
100 gdisplay: "live",
101 games: [],
102 challenges: [],
103 people: {},
104 infoMessage: "",
105 newchallenge: {
106 fen: "",
107 vid: localStorage.getItem("vid") || "",
108 to: "", //name of challenged player (if any)
109 cadence: localStorage.getItem("cadence") || "",
110 },
111 newChat: "",
112 conn: null,
113 connexionString: "",
114 // Related to (killing of) self multi-connects:
115 newConnect: {},
116 killed: {},
117 };
118 },
119 watch: {
120 // st.variants changes only once, at loading from [] to [...]
121 "st.variants": function(variantArray) {
122 // Set potential challenges and games variant names:
123 this.challenges.concat(this.games).forEach(o => {
124 if (o.vname == "")
125 o.vname = this.getVname(o.vid);
126 });
127 },
128 },
129 computed: {
130 anonymousCount: function() {
131 let count = 0;
132 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
133 return count;
134 },
135 },
136 created: function() {
137 const my = this.st.user;
138 this.$set(this.people, my.sid, {id:my.id, name:my.name, pages:["/"]});
139 // Ask server for current corr games (all but mines)
140 ajax(
141 "/games",
142 "GET",
143 {uid: this.st.user.id, excluded: true},
144 response => {
145 this.games = this.games.concat(response.games.map(g => {
146 const type = this.classifyObject(g);
147 const vname = this.getVname(g.vid);
148 return Object.assign({}, g, {type: type, vname: vname});
149 }));
150 }
151 );
152 // Also ask for corr challenges (open + sent by/to me)
153 ajax(
154 "/challenges",
155 "GET",
156 {uid: this.st.user.id},
157 response => {
158 // Gather all senders names, and then retrieve full identity:
159 // (TODO [perf]: some might be online...)
160 let names = {};
161 response.challenges.forEach(c => {
162 if (c.uid != this.st.user.id)
163 names[c.uid] = ""; //unknwon for now
164 else if (!!c.target && c.target != this.st.user.id)
165 names[c.target] = "";
166 });
167 const addChallenges = (newChalls) => {
168 names[this.st.user.id] = this.st.user.name; //in case of
169 this.challenges = this.challenges.concat(
170 response.challenges.map(c => {
171 const from = {name: names[c.uid], id: c.uid}; //or just name
172 const type = this.classifyObject(c);
173 const vname = this.getVname(c.vid);
174 return Object.assign({},
175 {
176 type: type,
177 vname: vname,
178 from: from,
179 to: (!!c.target ? names[c.target] : ""),
180 },
181 c);
182 })
183 );
184 };
185 if (Object.keys(names).length > 0)
186 {
187 ajax("/users",
188 "GET",
189 { ids: Object.keys(names).join(",") },
190 response2 => {
191 response2.users.forEach(u => {names[u.id] = u.name});
192 addChallenges();
193 }
194 );
195 }
196 else
197 addChallenges();
198 }
199 );
200 const connectAndPoll = () => {
201 this.send("connect");
202 this.send("pollclientsandgamers");
203 };
204 // Initialize connection
205 this.connexionString = params.socketUrl +
206 "/?sid=" + this.st.user.sid +
207 "&tmpId=" + getRandString() +
208 "&page=" + encodeURIComponent(this.$route.path);
209 this.conn = new WebSocket(this.connexionString);
210 this.conn.onopen = connectAndPoll;
211 this.conn.onmessage = this.socketMessageListener;
212 this.conn.onclose = this.socketCloseListener;
213 },
214 mounted: function() {
215 ["peopleWrap","infoDiv","newgameDiv"].forEach(eltName => {
216 let elt = document.getElementById(eltName);
217 elt.addEventListener("click", processModalClick);
218 });
219 document.querySelectorAll("#predefinedCadences > button").forEach(
220 (b) => { b.addEventListener("click",
221 () => { this.newchallenge.cadence = b.innerHTML; }
222 )}
223 );
224 const showCtype = localStorage.getItem("type-challenges") || "live";
225 const showGtype = localStorage.getItem("type-games") || "live";
226 this.setDisplay('c', showCtype);
227 this.setDisplay('g', showGtype);
228 },
229 beforeDestroy: function() {
230 this.send("disconnect");
231 },
232 methods: {
233 // Helpers:
234 send: function(code, obj) {
235 if (!!this.conn)
236 {
237 this.conn.send(JSON.stringify(
238 Object.assign(
239 {code: code},
240 obj,
241 )
242 ));
243 }
244 },
245 getVname: function(vid) {
246 const variant = this.st.variants.find(v => v.id == vid);
247 // this.st.variants might be uninitialized (variant == null)
248 return (!!variant ? variant.name : "");
249 },
250 filterChallenges: function(type) {
251 return this.challenges.filter(c => c.type == type);
252 },
253 filterGames: function(type) {
254 return this.games.filter(g => g.type == type);
255 },
256 classifyObject: function(o) { //challenge or game
257 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
258 },
259 setDisplay: function(letter, type, e) {
260 this[letter + "display"] = type;
261 localStorage.setItem("type-" + (letter == 'c' ? "challenges" : "games"), type);
262 let elt = !!e
263 ? e.target
264 : document.getElementById("btn" + letter.toUpperCase() + type);
265 elt.classList.add("active");
266 elt.classList.remove("somethingnew"); //in case of
267 if (!!elt.previousElementSibling)
268 elt.previousElementSibling.classList.remove("active");
269 else
270 elt.nextElementSibling.classList.remove("active");
271 },
272 isGamer: function(sid) {
273 return this.people[sid].pages.some(p => p.indexOf("/game/") >= 0);
274 },
275 getActionLabel: function(sid) {
276 return this.people[sid].pages.some(p => p == "/")
277 ? "Challenge"
278 : "Observe";
279 },
280 challOrWatch: function(sid) {
281 if (this.people[sid].pages.some(p => p == "/"))
282 {
283 // Available, in Hall
284 this.newchallenge.to = this.people[sid].name;
285 document.getElementById("modalPeople").checked = false;
286 doClick("modalNewgame");
287 }
288 else
289 {
290 // In some game, maybe playing maybe not: show a random one
291 let gids = [];
292 this.people[sid].pages.forEach(p => {
293 const matchGid = p.match(/[a-zA-Z0-9]+$/);
294 if (!!matchGid)
295 gids.push(matchGid[0]);
296 });
297 const gid = gids[Math.floor(Math.random() * gids.length)];
298 this.showGame(this.games.find(g => g.id == gid));
299 }
300 },
301 showGame: function(g) {
302 // NOTE: we are an observer, since only games I don't play are shown here
303 // ==> Moves sent by connected remote player(s) if live game
304 let url = "/game/" + g.id;
305 if (g.type == "live")
306 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
307 this.$router.push(url);
308 },
309 resetChatColor: function() {
310 // TODO: this is called twice, once on opening an once on closing
311 document.getElementById("peopleBtn").classList.remove("somethingnew");
312 },
313 processChat: function(chat) {
314 this.send("newchat", {data:chat});
315 },
316 // Messaging center:
317 socketMessageListener: function(msg) {
318 if (!this.conn)
319 return;
320 const data = JSON.parse(msg.data);
321 switch (data.code)
322 {
323 case "pollclientsandgamers":
324 {
325 // Since people can be both in Hall and Game,
326 // need to track "askIdentity" requests:
327 let identityAsked = {};
328 data.sockIds.forEach(s => {
329 const page = s.page || "/";
330 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
331 {
332 identityAsked[s.sid] = true;
333 this.send("askidentity", {target:s.sid, page:page});
334 }
335 if (!this.people[s.sid])
336 this.$set(this.people, s.sid, {id:0, name:"", pages:[page]});
337 else if (this.people[s.sid].pages.indexOf(page) < 0)
338 this.people[s.sid].pages.push(page);
339 if (!s.page) //peer is in Hall
340 this.send("askchallenge", {target:s.sid});
341 else //peer is in Game
342 this.send("askgame", {target:s.sid, page:page});
343 });
344 break;
345 }
346 case "connect":
347 case "gconnect":
348 {
349 const page = data.page || "/";
350 // NOTE: player could have been polled earlier, but might have logged in then
351 // So it's a good idea to ask identity if he was anonymous.
352 // But only ask game / challenge if currently disconnected.
353 if (!this.people[data.from])
354 {
355 this.$set(this.people, data.from, {name:"", id:0, pages:[page]});
356 if (data.code == "connect")
357 this.send("askchallenge", {target:data.from});
358 else
359 this.send("askgame", {target:data.from, page:page});
360 }
361 else
362 {
363 // append page if not already in list
364 if (this.people[data.from].pages.indexOf(page) < 0)
365 this.people[data.from].pages.push(page);
366 }
367 if (this.people[data.from].id == 0)
368 {
369 this.newConnect[data.from] = true; //for self multi-connects tests
370 this.send("askidentity", {target:data.from, page:page});
371 }
372 break;
373 }
374 case "disconnect":
375 case "gdisconnect":
376 // If the user reloads the page twice very quickly (experienced with Firefox),
377 // the first reload won't have time to connect but will trigger a "close" event anyway.
378 // ==> Next check is required.
379 if (!this.people[data.from])
380 return;
381 // Disconnect means no more tmpIds:
382 if (data.code == "disconnect")
383 {
384 // Remove the live challenge sent by this player:
385 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
386 }
387 else
388 {
389 // Remove the matching live game if now unreachable
390 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
391 const gidx = this.games.findIndex(g => g.id == gid);
392 if (gidx >= 0)
393 {
394 const game = this.games[gidx];
395 if (game.type == "live" &&
396 game.rids.length == 1 && game.rids[0] == data.from)
397 {
398 this.games.splice(gidx, 1);
399 }
400 }
401 }
402 const page = data.page || "/";
403 ArrayFun.remove(this.people[data.from].pages, p => p == page);
404 if (this.people[data.from].pages.length == 0)
405 this.$delete(this.people, data.from);
406 break;
407 case "killed":
408 // I logged in elsewhere:
409 alert(this.st.tr["New connexion detected: tab now offline"]);
410 // TODO: this fails. See https://github.com/websockets/ws/issues/489
411 //this.conn.removeEventListener("message", this.socketMessageListener);
412 //this.conn.removeEventListener("close", this.socketCloseListener);
413 //this.conn.close();
414 this.conn = null;
415 break;
416 case "askidentity":
417 {
418 // Request for identification (TODO: anonymous shouldn't need to reply)
419 const me = {
420 // Decompose to avoid revealing email
421 name: this.st.user.name,
422 sid: this.st.user.sid,
423 id: this.st.user.id,
424 };
425 this.send("identity", {data:me, target:data.from});
426 break;
427 }
428 case "identity":
429 {
430 const user = data.data;
431 if (!!user.name) //otherwise anonymous
432 {
433 // If I multi-connect, kill current connexion if no mark (I'm older)
434 if (this.newConnect[user.sid] && user.id > 0
435 && user.id == this.st.user.id && user.sid != this.st.user.sid)
436 {
437 if (!this.killed[this.st.user.sid])
438 {
439 this.send("killme", {sid:this.st.user.sid});
440 this.killed[this.st.user.sid] = true;
441 }
442 }
443 if (user.sid != this.st.user.sid) //I already know my identity...
444 {
445 this.$set(this.people, user.sid,
446 {
447 id: user.id,
448 name: user.name,
449 pages: this.people[user.sid].pages,
450 });
451 }
452 }
453 delete this.newConnect[user.sid];
454 break;
455 }
456 case "askchallenge":
457 {
458 // Send my current live challenge (if any)
459 const cIdx = this.challenges.findIndex(c =>
460 c.from.sid == this.st.user.sid && c.type == "live");
461 if (cIdx >= 0)
462 {
463 const c = this.challenges[cIdx];
464 // NOTE: in principle, should only send targeted challenge to the target.
465 // But we may not know yet the identity of the target (just name),
466 // so cannot decide if data.from is the target or not.
467 const myChallenge =
468 {
469 id: c.id,
470 from: this.st.user.sid,
471 to: c.to,
472 fen: c.fen,
473 vid: c.vid,
474 cadence: c.cadence,
475 added: c.added,
476 };
477 this.send("challenge", {data:myChallenge, target:data.from});
478 }
479 break;
480 }
481 case "challenge": //after "askchallenge"
482 case "newchallenge":
483 {
484 // NOTE about next condition: see "askchallenge" case.
485 const chall = data.data;
486 if (!chall.to || (this.people[chall.from].id > 0 &&
487 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
488 {
489 let newChall = Object.assign({}, chall);
490 newChall.type = this.classifyObject(chall);
491 newChall.added = Date.now();
492 let fromValues = Object.assign({}, this.people[chall.from]);
493 delete fromValues["pages"]; //irrelevant in this context
494 newChall.from = Object.assign({sid:chall.from}, fromValues);
495 newChall.vname = this.getVname(newChall.vid);
496 this.challenges.push(newChall);
497 if ((newChall.type == "live" && this.cdisplay == "corr") ||
498 (newChall.type == "corr" && this.cdisplay == "live"))
499 {
500 document.getElementById("btnC" + newChall.type).classList.add("somethingnew");
501 }
502 }
503 break;
504 }
505 case "refusechallenge":
506 {
507 const cid = data.data;
508 ArrayFun.remove(this.challenges, c => c.id == cid);
509 alert(this.st.tr["Challenge declined"]);
510 break;
511 }
512 case "deletechallenge":
513 {
514 // NOTE: the challenge may be already removed
515 const cid = data.data;
516 ArrayFun.remove(this.challenges, c => c.id == cid);
517 break;
518 }
519 case "game": //individual request
520 case "newgame":
521 {
522 // NOTE: it may be live or correspondance
523 const game = data.data;
524 let locGame = this.games.find(g => g.id == game.id);
525 if (!locGame)
526 {
527 let newGame = game;
528 newGame.type = this.classifyObject(game);
529 newGame.vname = this.getVname(game.vid);
530 if (!game.score) //if new game from Hall
531 newGame.score = "*";
532 newGame.rids = [game.rid];
533 delete newGame["rid"];
534 this.games.push(newGame);
535 if ((newGame.type == "live" && this.gdisplay == "corr") ||
536 (newGame.type == "corr" && this.gdisplay == "live"))
537 {
538 document.getElementById("btnG" + newGame.type).classList.add("somethingnew");
539 }
540 }
541 else
542 {
543 // Append rid (if not already in list)
544 if (!locGame.rids.includes(game.rid))
545 locGame.rids.push(game.rid);
546 }
547 break;
548 }
549 case "result":
550 {
551 let g = this.games.find(g => g.id == data.gid);
552 if (!!g)
553 g.score = data.score;
554 break;
555 }
556 case "startgame":
557 {
558 // New game just started: data contain all information
559 const gameInfo = data.data;
560 if (this.classifyObject(gameInfo) == "live")
561 this.startNewGame(gameInfo);
562 else
563 {
564 this.infoMessage = this.st.tr["New correspondance game:"] +
565 " <a href='#/game/" + gameInfo.id + "'>" +
566 "#/game/" + gameInfo.id + "</a>";
567 let modalBox = document.getElementById("modalInfo");
568 modalBox.checked = true;
569 }
570 break;
571 }
572 case "newchat":
573 this.newChat = data.data;
574 if (!document.getElementById("modalPeople").checked)
575 document.getElementById("peopleBtn").classList.add("somethingnew");
576 break;
577 }
578 },
579 socketCloseListener: function() {
580 if (!this.conn)
581 return;
582 this.conn = new WebSocket(this.connexionString);
583 this.conn.addEventListener("message", this.socketMessageListener);
584 this.conn.addEventListener("close", this.socketCloseListener);
585 },
586 // Challenge lifecycle:
587 newChallenge: async function() {
588 if (this.newchallenge.vid == "")
589 return alert(this.st.tr["Please select a variant"]);
590 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
591 return alert(this.st.tr["Self-challenge is forbidden"]);
592 const vname = this.getVname(this.newchallenge.vid);
593 const vModule = await import("@/variants/" + vname + ".js");
594 window.V = vModule.VariantRules;
595 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
596 this.newchallenge.cadence += "+0"; //assume minutes, no increment
597 const error = checkChallenge(this.newchallenge);
598 if (!!error)
599 return alert(error);
600 const ctype = this.classifyObject(this.newchallenge);
601 if (ctype == "corr" && this.st.user.id <= 0)
602 return alert(this.st.tr["Please log in to play correspondance games"]);
603 // NOTE: "from" information is not required here
604 let chall = Object.assign({}, this.newchallenge);
605 const finishAddChallenge = (cid) => {
606 chall.id = cid || "c" + getRandString();
607 // Remove old challenge if any (only one at a time of a given type):
608 const cIdx = this.challenges.findIndex(c =>
609 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
610 if (cIdx >= 0)
611 {
612 // Delete current challenge (will be replaced now)
613 this.send("deletechallenge", {data:this.challenges[cIdx].id});
614 if (ctype == "corr")
615 {
616 ajax(
617 "/challenges",
618 "DELETE",
619 {id: this.challenges[cIdx].id}
620 );
621 }
622 this.challenges.splice(cIdx, 1);
623 }
624 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
625 // Add new challenge:
626 chall.from = { //decompose to avoid revealing email
627 sid: this.st.user.sid,
628 id: this.st.user.id,
629 name: this.st.user.name,
630 };
631 chall.added = Date.now();
632 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
633 chall.type = ctype;
634 chall.vname = vname;
635 this.challenges.push(chall);
636 // Remember cadence + vid for quicker further challenges:
637 localStorage.setItem("cadence", chall.cadence);
638 localStorage.setItem("vid", chall.vid);
639 document.getElementById("modalNewgame").checked = false;
640 };
641 if (ctype == "live")
642 {
643 // Live challenges have a random ID
644 finishAddChallenge(null);
645 }
646 else
647 {
648 // Correspondance game: send challenge to server
649 ajax(
650 "/challenges",
651 "POST",
652 { chall: chall },
653 response => { finishAddChallenge(response.cid); }
654 );
655 }
656 },
657 clickChallenge: function(c) {
658 const myChallenge = (c.from.sid == this.st.user.sid //live
659 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
660 if (!myChallenge)
661 {
662 if (c.type == "corr" && this.st.user.id <= 0)
663 return alert(this.st.tr["Please log in to accept corr challenges"]);
664 c.accepted = true;
665 if (!!c.to) //c.to == this.st.user.name (connected)
666 {
667 // TODO: if special FEN, show diagram after loading variant
668 c.accepted = confirm("Accept challenge?");
669 }
670 if (c.accepted)
671 {
672 c.seat = { //again, avoid c.seat = st.user to not reveal email
673 sid: this.st.user.sid,
674 id: this.st.user.id,
675 name: this.st.user.name,
676 };
677 this.launchGame(c);
678 }
679 else
680 {
681 this.send("refusechallenge", {data:c.id, target:c.from.sid});
682 }
683 this.send("deletechallenge", {data:c.id});
684 }
685 else //my challenge
686 {
687 if (c.type == "corr")
688 {
689 ajax(
690 "/challenges",
691 "DELETE",
692 {id: c.id}
693 );
694 }
695 this.send("deletechallenge", {data:c.id});
696 }
697 // In all cases, the challenge is consumed:
698 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
699 },
700 // NOTE: when launching game, the challenge is already being deleted
701 launchGame: async function(c) {
702 const vModule = await import("@/variants/" + c.vname + ".js");
703 window.V = vModule.VariantRules;
704 // These game informations will be shared
705 let gameInfo =
706 {
707 id: getRandString(),
708 fen: c.fen || V.GenRandInitFen(),
709 players: shuffle([c.from, c.seat]), //white then black
710 vid: c.vid,
711 cadence: c.cadence,
712 };
713 let oppsid = c.from.sid; //may not be defined if corr + offline opp
714 if (!oppsid)
715 {
716 oppsid = Object.keys(this.people).find(sid =>
717 this.people[sid].id == c.from.id);
718 }
719 const notifyNewgame = () => {
720 if (!!oppsid) //opponent is online
721 this.send("startgame", {data:gameInfo, target:oppsid});
722 // Send game info (only if live) to everyone except me in this tab
723 this.send("newgame", {data:gameInfo});
724 };
725 if (c.type == "live")
726 {
727 notifyNewgame();
728 this.startNewGame(gameInfo);
729 }
730 else //corr: game only on server
731 {
732 ajax(
733 "/games",
734 "POST",
735 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
736 response => {
737 gameInfo.id = response.gameId;
738 notifyNewgame();
739 this.$router.push("/game/" + response.gameId);
740 }
741 );
742 }
743 },
744 // NOTE: for live games only (corr games start on the server)
745 startNewGame: function(gameInfo) {
746 const game = Object.assign({}, gameInfo, {
747 // (other) Game infos: constant
748 fenStart: gameInfo.fen,
749 vname: this.getVname(gameInfo.vid),
750 created: Date.now(),
751 // Game state (including FEN): will be updated
752 moves: [],
753 clocks: [-1, -1], //-1 = unstarted
754 initime: [0, 0], //initialized later
755 score: "*",
756 });
757 GameStorage.add(game);
758 if (this.st.settings.sound >= 1)
759 new Audio("/sounds/newgame.mp3").play().catch(err => {});
760 this.$router.push("/game/" + gameInfo.id);
761 },
762 },
763 };
764 </script>
765
766 <style lang="sass" scoped>
767 .active
768 color: #42a983
769
770 #infoDiv > .card
771 padding: 15px 0
772 max-width: 430px
773
774 #newgameDiv > .card
775 max-width: 767px
776 max-height: 100%
777
778 div#peopleWrap > .card
779 max-height: 100%
780
781 @media screen and (min-width: 1281px)
782 div#peopleWrap > .card
783 max-width: 66.67%
784
785 @media screen and (max-width: 1280px)
786 div#peopleWrap > .card
787 max-width: 83.33%
788
789 @media screen and (max-width: 767px)
790 div#peopleWrap > .card
791 max-width: 100%
792
793 #players
794 width: 50%
795 position: relative
796 float: left
797 #chat
798 width: 50%
799 float: left
800 position: relative
801 @media screen and (max-width: 767px)
802 #players, #chats
803 width: 100%
804 #chat > .card
805 max-width: 100%
806 margin: 0;
807 border: none;
808 #players > p
809 margin-left: 5px
810 .anonymous
811 font-style: italic
812 button.player-action
813 margin-left: 32px
814
815 .somethingnew
816 background-color: #c5fefe !important
817
818 .tabbtn
819 background-color: #f9faee
820
821 #div2, #div3
822 margin-top: 15px
823 @media screen and (max-width: 767px)
824 #div2, #div3
825 margin-top: 0
826 </style>