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