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