Fixes on login/logout + challenges sending
[vchess.git] / client / src / views / Hall.vue
CommitLineData
ccd4a2b7 1<template lang="pug">
9d58ef95 2main
dce792f6
BA
3 input#modalInfo.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="infoMessage")
5 .card.smallpad.small-modal.text-center
6 label.modal-close(for="modalInfo")
7 h3#infoMessage.section
3d55deea 8 p(v-html="infoMessage")
5b020e73 9 input#modalNewgame.modal(type="checkbox")
dcd68c41
BA
10 div(role="dialog" data-checkbox="modalNewgame"
11 aria-labelledby="titleFenedit")
c97830ea 12 .card.smallpad(@keyup.enter="newChallenge")
5b020e73
BA
13 label#closeNewgame.modal-close(for="modalNewgame")
14 fieldset
15 label(for="selectVariant") {{ st.tr["Variant"] }}
9d58ef95 16 select#selectVariant(v-model="newchallenge.vid")
85e5b5c1 17 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
5b020e73 18 fieldset
b4d619d1 19 label(for="timeControl") {{ st.tr["Time control"] }}
9d58ef95 20 input#timeControl(type="text" v-model="newchallenge.timeControl"
b4d619d1
BA
21 placeholder="3m+2s, 1h+30s, 7d+1d ...")
22 fieldset(v-if="st.user.id > 0")
9d58ef95 23 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
6fba6e0c 24 input#selectPlayers(type="text" v-model="newchallenge.to")
b4d619d1 25 fieldset(v-if="st.user.id > 0")
9d58ef95
BA
26 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
27 input#inputFen(type="text" v-model="newchallenge.fen")
b4d619d1 28 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
9d58ef95 29 .row
9ca1e26b
BA
30 .col-sm-12
31 button#newGame(onClick="doClick('modalNewgame')") New game
9d58ef95 32 .row
9ca1e26b 33 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
ed06d9e9
BA
34 div
35 .button-group
36 button(@click="(e) => setDisplay('c','live',e)" class="active")
37 | Live Challenges
38 button(@click="(e) => setDisplay('c','corr',e)")
39 | Correspondance challenges
40 ChallengeList(v-show="cdisplay=='live'"
41 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
42 ChallengeList(v-show="cdisplay=='corr'"
43 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
44 #people
45 h3.text-center Who's there?
46 #players
47 p(v-for="p in Object.values(people)" v-if="!!p.name")
48 span {{ p.name }}
49 button.player-action(
50 v-if="p.name != st.user.name"
51 @click="challOrWatch(p,$event)"
52 )
53 | {{ whatPlayerDoes(p) }}
54 p.anonymous @nonymous ({{ anonymousCount }})
55 #chat
56 Chat(:players="[]")
57 .clearer
58 div
59 .button-group
60 button(@click="(e) => setDisplay('g','live',e)" class="active")
61 | Live games
62 button(@click="(e) => setDisplay('g','corr',e)")
63 | Correspondance games
64 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
65 @show-game="showGame")
66 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
67 @show-game="showGame")
625022fd
BA
68</template>
69
70<script>
5b020e73 71import { store } from "@/store";
9d58ef95
BA
72import { checkChallenge } from "@/data/challengeCheck";
73import { ArrayFun } from "@/utils/array";
03608482 74import { ajax } from "@/utils/ajax";
4b0384fa 75import { getRandString, shuffle } from "@/utils/alea";
603b8a8b 76import Chat from "@/components/Chat.vue";
5b020e73
BA
77import GameList from "@/components/GameList.vue";
78import ChallengeList from "@/components/ChallengeList.vue";
967a2686 79import { GameStorage } from "@/utils/gameStorage";
625022fd 80export default {
cf2343ce 81 name: "my-hall",
5b020e73 82 components: {
603b8a8b 83 Chat,
5b020e73
BA
84 GameList,
85 ChallengeList,
86 },
fb54f098
BA
87 data: function () {
88 return {
5b020e73 89 st: store.state,
6855163c
BA
90 cdisplay: "live", //or corr
91 pdisplay: "players", //or chat
fb54f098 92 gdisplay: "live",
6855163c 93 games: [],
b4d619d1 94 challenges: [],
dcd68c41 95 people: {}, //people in main hall
3d55deea 96 infoMessage: "",
9d58ef95 97 newchallenge: {
fb54f098
BA
98 fen: "",
99 vid: 0,
6fba6e0c 100 to: "", //name of challenged player (if any)
6faa92f2 101 timeControl: "", //"2m+2s" ...etc
fb54f098
BA
102 },
103 };
104 },
fd7aea36
BA
105 watch: {
106 // st.variants changes only once, at loading from [] to [...]
107 "st.variants": function(variantArray) {
108 // Set potential challenges and games variant names:
109 this.challenges.forEach(c => {
110 if (c.vname == "")
111 c.vname = this.getVname(c.vid);
112 });
113 this.games.forEach(g => {
114 if (g.vname == "")
f41ce580 115 g.vname = this.getVname(g.vid);
fd7aea36
BA
116 });
117 },
118 },
b4d619d1 119 computed: {
ed06d9e9
BA
120 anonymousCount: function() {
121 let count = 0;
122 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
123 return count;
b4d619d1
BA
124 },
125 },
9d58ef95 126 created: function() {
4d64881e 127 // Always add myself to players' list
66d03f23 128 const my = this.st.user;
dcd68c41 129 this.$set(this.people, my.sid, {id:my.id, name:my.name});
f6f2bef1
BA
130 // Retrieve live challenge (not older than 30 minute) if any:
131 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
132 if (!!chall)
133 {
134 if ((Date.now() - chall.added)/1000 <= 30*60)
135 this.challenges.push(chall);
136 else
137 localStorage.removeItem("challenge");
138 }
3d55deea
BA
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 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 const uids = response.challenges.map(c => { return c.uid });
161 ajax("/users",
162 "GET",
163 { ids: uids.join(",") },
164 response2 => {
165 let names = {};
166 response2.users.forEach(u => {names[u.id] = u.name});
167 this.challenges = this.challenges.concat(
168 response.challenges.map(c => {
169 // (just players names in fact)
170 const from = {name: names[c.uid], id: c.uid};
171 const type = this.classifyObject(c);
172 const vname = this.getVname(c.vid);
173 return Object.assign({}, c, {type: type, vname: vname, from: from});
174 })
175 )
176 }
177 );
178 }
179 );
2ada153c 180 // 0.1] Ask server for room composition:
7b01e447 181 const funcPollClients = () => {
ed06d9e9
BA
182 // Same strategy as in Game.vue: send connection
183 // after we're sure WebSocket is initialized
184 this.st.conn.send(JSON.stringify({code:"connect"}));
81d9ce72 185 this.st.conn.send(JSON.stringify({code:"pollclients"}));
4d64881e 186 };
7b01e447
BA
187 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
188 funcPollClients();
189 else //socket not ready yet (initial loading)
3cb412e9 190 this.st.conn.onopen = funcPollClients;
4d64881e
BA
191 this.st.conn.onmessage = this.socketMessageListener;
192 const socketCloseListener = () => {
cdb34c93 193 store.socketCloseListener(); //reinitialize connexion (in store.js)
4d64881e
BA
194 this.st.conn.addEventListener('message', this.socketMessageListener);
195 this.st.conn.addEventListener('close', socketCloseListener);
196 };
197 this.st.conn.onclose = socketCloseListener;
9d58ef95 198 },
fb54f098 199 methods: {
a6bddfc6 200 // Helpers:
6855163c
BA
201 filterChallenges: function(type) {
202 return this.challenges.filter(c => c.type == type);
203 },
204 filterGames: function(type) {
a9b131f1 205 return this.games.filter(g => g.type == type);
6855163c 206 },
2ada153c 207 classifyObject: function(o) { //challenge or game
6855163c 208 // Heuristic: should work for most cases... (TODO)
2ada153c 209 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
6855163c 210 },
2ada153c 211 showGame: function(g) {
5bd05dba 212 // NOTE: we are an observer, since only games I don't play are shown here
2ada153c 213 // ==> Moves sent by connected remote player(s) if live game
d9b86b16 214 let url = "/game/" + g.id;
2ada153c 215 if (g.type == "live")
dc284d90 216 url += "?rid=" + g.rid;
2ada153c 217 this.$router.push(url);
a6bddfc6 218 },
5bcc9b31
BA
219 setDisplay: function(letter, type, e) {
220 this[letter + "display"] = type;
221 e.target.classList.add("active");
222 if (!!e.target.previousElementSibling)
223 e.target.previousElementSibling.classList.remove("active");
224 else
225 e.target.nextElementSibling.classList.remove("active");
226 },
a6bddfc6 227 getVname: function(vid) {
f41ce580
BA
228 const variant = this.st.variants.find(v => v.id == vid);
229 // this.st.variants might be uninitialized (variant == null)
230 return (!!variant ? variant.name : "");
a6bddfc6 231 },
dcd68c41 232 whatPlayerDoes: function(p) {
41c80bb6
BA
233 if (this.games.some(g => g.type == "live"
234 && g.players.some(pl => pl.sid == p.sid)))
235 {
dcd68c41 236 return "Playing";
41c80bb6 237 }
dcd68c41 238 return "Challenge"; //player is available
5bd05dba 239 },
a6bddfc6
BA
240 sendSomethingTo: function(to, code, obj, warnDisconnected) {
241 const doSend = (code, obj, sid) => {
242 this.st.conn.send(JSON.stringify(Object.assign(
a6bddfc6
BA
243 {code: code},
244 obj,
245 {target: sid}
246 )));
247 };
c9695cb1 248 if (!!to)
a6bddfc6 249 {
c9695cb1 250 // Challenge with targeted players
dcd68c41
BA
251 const targetSid =
252 Object.keys(this.people).find(sid => this.people[sid].name == to);
c9695cb1
BA
253 if (!targetSid)
254 {
255 if (!!warnDisconnected)
5ea8d113
BA
256 alert("Warning: " + to + " is not connected");
257 return false;
c9695cb1
BA
258 }
259 else
260 doSend(code, obj, targetSid);
a6bddfc6
BA
261 }
262 else
263 {
5ea8d113 264 // Open challenge: send to all connected players (me excepted)
dcd68c41
BA
265 Object.keys(this.people).forEach(sid => {
266 if (sid != this.st.user.sid)
267 doSend(code, obj, sid);
a6bddfc6
BA
268 });
269 }
5ea8d113 270 return true;
a6bddfc6
BA
271 },
272 // Messaging center:
9d58ef95
BA
273 socketMessageListener: function(msg) {
274 const data = JSON.parse(msg.data);
275 switch (data.code)
276 {
6d9f4315
BA
277 case "duplicate":
278 alert("Warning: duplicate 'offline' connection");
279 break;
f4f4c03c 280 // 0.2] Receive clients list (just socket IDs)
81d9ce72 281 case "pollclients":
1efe1d79 282 {
5a3da968 283 data.sockIds.forEach(sid => {
dcd68c41 284 this.$set(this.people, sid, {id:0, name:""});
81d9ce72 285 // Ask identity, challenges and game(s)
5a3da968 286 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
2ada153c 287 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
5a3da968 288 });
cd0d7743
BA
289 // Also ask current games to all playing peers (TODO: some design issue)
290 this.st.conn.send(JSON.stringify({code:"askgames"}));
5a3da968 291 break;
1efe1d79 292 }
81d9ce72 293 case "askidentity":
1efe1d79 294 {
6855163c
BA
295 // Request for identification: reply if I'm not anonymous
296 if (this.st.user.id > 0)
297 {
dcd68c41
BA
298 this.st.conn.send(JSON.stringify({code:"identity",
299 user: {
300 // NOTE: decompose to avoid revealing email
301 name: this.st.user.name,
302 sid: this.st.user.sid,
303 id: this.st.user.id,
304 },
305 target:data.from}));
6855163c 306 }
5a3da968 307 break;
1efe1d79 308 }
dcd68c41
BA
309 case "identity":
310 {
311 this.$set(this.people, data.user.sid,
312 {id: data.user.id, name: data.user.name});
313 break;
314 }
dd75774d 315 case "askchallenge":
1efe1d79 316 {
6855163c 317 // Send my current live challenge (if any)
5ea8d113
BA
318 const cIdx = this.challenges.findIndex(c =>
319 c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
320 if (cIdx >= 0)
321 {
322 const c = this.challenges[cIdx];
5ea8d113
BA
323 if (!!c.to)
324 {
325 // Only share targeted challenges to the targets:
326 const toSid = Object.keys(this.people).find(k =>
327 this.people[k].name == c.to);
328 if (toSid != data.from)
329 return;
330 }
dd75774d
BA
331 const myChallenge =
332 {
81d9ce72 333 // Minimal challenge informations: (from not required)
2ada153c 334 id: c.id,
81d9ce72
BA
335 to: c.to,
336 fen: c.fen,
337 vid: c.vid,
5ea8d113 338 timeControl: c.timeControl,
dd75774d
BA
339 };
340 this.st.conn.send(JSON.stringify({code:"challenge",
42c15a75 341 chall:myChallenge, target:data.from}));
81d9ce72
BA
342 }
343 break;
1efe1d79 344 }
dd75774d 345 case "challenge":
1efe1d79 346 {
dd75774d 347 // Receive challenge from some player (+sid)
6855163c 348 let newChall = data.chall;
2ada153c 349 newChall.type = this.classifyObject(data.chall);
dcd68c41
BA
350 newChall.from =
351 Object.assign({sid:data.from}, this.people[data.from]);
42c15a75 352 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
25996aed 353 newChall.vname = this.getVname(newChall.vid);
6855163c 354 this.challenges.push(newChall);
81d9ce72 355 break;
1efe1d79 356 }
dd75774d 357 case "game":
1efe1d79 358 {
6855163c 359 // Receive game from some player (+sid)
6855163c 360 // NOTE: it may be correspondance (if newgame while we are connected)
5bcc9b31 361 if (this.games.every(g => g.id != data.game.id)) //ignore duplicates
d9b86b16
BA
362 {
363 let newGame = data.game;
364 newGame.type = this.classifyObject(data.game);
a9b131f1 365 newGame.vname = this.getVname(data.game.vid);
d9b86b16
BA
366 newGame.rid = data.from;
367 newGame.score = "*";
368 this.games.push(newGame);
369 }
81d9ce72 370 break;
1efe1d79 371 }
9d58ef95 372 case "newgame":
1efe1d79 373 {
66d03f23
BA
374 // TODO: next line required ?!
375 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
5d04793e 376 // New game just started: data contain all information
66d03f23 377 if (this.classifyObject(data.gameInfo) == "live")
5d04793e 378 this.startNewGame(data.gameInfo);
5d04793e
BA
379 else
380 {
3d55deea 381 this.infoMessage = "New game started: " +
11667c79
BA
382 "<a href='#/game/" + data.gameInfo.id + "'>" +
383 "#/game/" + data.gameInfo.id + "</a>";
dce792f6
BA
384 let modalBox = document.getElementById("modalInfo");
385 modalBox.checked = true;
3d55deea 386 setTimeout(() => { modalBox.checked = false; }, 3000);
5d04793e 387 }
9d58ef95 388 break;
1efe1d79 389 }
bb7dd7db
BA
390 case "refusechallenge":
391 {
5bd05dba 392 ArrayFun.remove(this.challenges, c => c.id == data.cid);
5ea8d113 393 alert(this.people[data.from].name + " declined your challenge");
bb7dd7db
BA
394 break;
395 }
1efe1d79
BA
396 case "deletechallenge":
397 {
1ba761c8 398 // NOTE: the challenge may be already removed
9d58ef95 399 ArrayFun.remove(this.challenges, c => c.id == data.cid);
66d03f23 400 localStorage.removeItem("challenge"); //in case of
9d58ef95 401 break;
1efe1d79 402 }
b4d619d1 403 case "connect":
1efe1d79 404 {
dcd68c41 405 this.$set(this.people, data.from, {name:"", id:0});
c6788ecf
BA
406 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
407 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
408 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
9d58ef95 409 break;
1efe1d79 410 }
b4d619d1 411 case "disconnect":
1efe1d79 412 {
dcd68c41 413 this.$delete(this.people, data.from);
a6bddfc6 414 // Also remove all challenges sent by this player:
c6788ecf 415 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
2ada153c
BA
416 // And all live games where he plays and no other opponent is online
417 ArrayFun.remove(this.games, g =>
c6788ecf 418 g.type == "live" && (g.players.every(p => p.sid == data.from
dcd68c41 419 || !this.people[p.sid])), "all");
9d58ef95 420 break;
1efe1d79 421 }
9d58ef95
BA
422 }
423 },
a6bddfc6 424 // Challenge lifecycle:
b4d619d1
BA
425 tryChallenge: function(player) {
426 if (player.id == 0)
427 return; //anonymous players cannot be challenged
a7808884 428 this.newchallenge.to = player.name;
b4d619d1 429 doClick("modalNewgame");
fb54f098 430 },
dcd68c41
BA
431 challOrWatch: function(p, e) {
432 switch (e.target.innerHTML)
433 {
434 case "Challenge":
435 this.tryChallenge(p);
436 break;
437 case "Playing":
438 // NOTE: this search for game was already done for rendering
439 this.showGame(this.games.find(
41c80bb6 440 g => g.type=="live" && g.players.some(pl => pl.sid == p.sid)));
dcd68c41
BA
441 break;
442 };
443 },
9d58ef95 444 newChallenge: async function() {
bb7dd7db 445 const vname = this.getVname(this.newchallenge.vid);
1efe1d79
BA
446 const vModule = await import("@/variants/" + vname + ".js");
447 window.V = vModule.VariantRules;
dcd68c41
BA
448 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
449 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
9d58ef95
BA
450 const error = checkChallenge(this.newchallenge);
451 if (!!error)
452 return alert(error);
2ada153c 453 const ctype = this.classifyObject(this.newchallenge);
098cd7f1
BA
454 if (ctype == "corr" && this.st.user.id <= 0)
455 return alert("Please log in to play correspondance games");
bb7dd7db 456 // NOTE: "from" information is not required here
a7808884 457 let chall = Object.assign({}, this.newchallenge);
2ada153c 458 const finishAddChallenge = (cid,warnDisconnected) => {
1efe1d79 459 chall.id = cid || "c" + getRandString();
2ada153c 460 // Send challenge to peers (if connected)
5ea8d113
BA
461 const isSent = this.sendSomethingTo(chall.to, "challenge",
462 {chall:chall}, !!warnDisconnected);
463 if (!isSent)
464 return;
465 // Remove old challenge if any (only one at a time):
466 const cIdx = this.challenges.findIndex(c =>
467 c.from.sid == this.st.user.sid && c.type == ctype);
468 if (cIdx >= 0)
469 {
470 // Delete current challenge (will be replaced now)
471 this.sendSomethingTo(this.challenges[cIdx].to,
472 "deletechallenge", {cid:this.challenges[cIdx].id});
473 if (ctype == "corr")
474 {
475 ajax(
476 "/challenges",
477 "DELETE",
478 {id: this.challenges[cIdx].id}
479 );
480 }
481 this.challenges.splice(cIdx, 1);
482 }
483 // Add new challenge:
1efe1d79 484 chall.added = Date.now();
a9b131f1 485 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
bb7dd7db
BA
486 chall.type = ctype;
487 chall.vname = vname;
dcd68c41
BA
488 chall.from = { //decompose to avoid revealing email
489 sid: this.st.user.sid,
490 id: this.st.user.id,
491 name: this.st.user.name,
492 };
1efe1d79 493 this.challenges.push(chall);
f41ce580
BA
494 if (ctype == "live")
495 localStorage.setItem("challenge", JSON.stringify(chall));
b4d619d1
BA
496 document.getElementById("modalNewgame").checked = false;
497 };
1efe1d79
BA
498 if (ctype == "live")
499 {
500 // Live challenges have a random ID
2ada153c 501 finishAddChallenge(null, "warnDisconnected");
03608482 502 }
b4d619d1 503 else
03608482 504 {
b4d619d1 505 // Correspondance game: send challenge to server
03608482 506 ajax(
1efe1d79 507 "/challenges",
03608482 508 "POST",
bebcc8d4 509 { chall: chall },
1efe1d79 510 response => { finishAddChallenge(response.cid); }
03608482 511 );
9d58ef95 512 }
fb54f098 513 },
a6bddfc6 514 clickChallenge: function(c) {
485fccd5
BA
515 const myChallenge = (c.from.sid == this.st.user.sid //live
516 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
517 if (!myChallenge)
a6bddfc6 518 {
3d55deea
BA
519 if (c.type == "corr" && this.st.user.id <= 0)
520 return alert("Please log in to accept corr challenges");
a6bddfc6 521 c.accepted = true;
485fccd5 522 if (!!c.to) //c.to == this.st.user.name (connected)
a6bddfc6
BA
523 {
524 // TODO: if special FEN, show diagram after loading variant
525 c.accepted = confirm("Accept challenge?");
526 }
485fccd5 527 if (c.accepted)
36093eba 528 {
dcd68c41
BA
529 c.seat = { //again, avoid c.seat = st.user to not reveal email
530 sid: this.st.user.sid,
531 id: this.st.user.id,
532 name: this.st.user.name,
533 };
485fccd5
BA
534 this.launchGame(c);
535 }
536 else
537 {
538 this.st.conn.send(JSON.stringify({
539 code: "refusechallenge",
540 cid: c.id, target: c.from.sid}));
36093eba 541 }
5ea8d113 542 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
a6bddfc6 543 }
2be5d614 544 else //my challenge
485fccd5 545 {
2be5d614
BA
546 if (c.type == "corr")
547 {
548 ajax(
549 "/challenges",
550 "DELETE",
551 {id: c.id}
552 );
553 }
f41ce580
BA
554 else //live
555 localStorage.removeItem("challenge");
5ea8d113 556 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
485fccd5 557 }
5ea8d113 558 // In all cases, the challenge is consumed:
3d55deea 559 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
a6bddfc6 560 },
485fccd5 561 // NOTE: when launching game, the challenge is already deleted
36093eba 562 launchGame: async function(c) {
a9b131f1 563 const vModule = await import("@/variants/" + c.vname + ".js");
a6bddfc6 564 window.V = vModule.VariantRules;
4b0384fa
BA
565 // These game informations will be sent to other players
566 const gameInfo =
a6bddfc6 567 {
11667c79 568 id: getRandString(),
a6bddfc6 569 fen: c.fen || V.GenRandInitFen(),
5d04793e 570 players: shuffle([c.from, c.seat]), //white then black
a6bddfc6 571 vid: c.vid,
f41ce580 572 vname: c.vname, //theoretically vid is enough, but much easier with vname
a9b131f1 573 timeControl: c.timeControl,
a6bddfc6 574 };
5ea8d113
BA
575 let oppsid = c.from.sid; //may not be defined if corr + offline opp
576 if (!oppsid)
8c564f46 577 {
5ea8d113 578 oppsid = Object.keys(this.people).find(sid =>
dcd68c41 579 this.people[sid].id == c.from.id);
8c564f46 580 }
411d23cd 581 const tryNotifyOpponent = () => {
5ea8d113 582 if (!!oppsid) //opponent is online
411d23cd
BA
583 {
584 this.st.conn.send(JSON.stringify({code:"newgame",
5ea8d113 585 gameInfo:gameInfo, target:oppsid, cid:c.id}));
411d23cd
BA
586 }
587 };
485fccd5 588 if (c.type == "live")
411d23cd
BA
589 {
590 tryNotifyOpponent();
485fccd5 591 this.startNewGame(gameInfo);
411d23cd 592 }
485fccd5
BA
593 else //corr: game only on server
594 {
595 ajax(
596 "/games",
597 "POST",
2be5d614 598 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
411d23cd 599 response => {
11667c79 600 gameInfo.id = response.gameId;
411d23cd
BA
601 tryNotifyOpponent();
602 this.$router.push("/game/" + response.gameId);
603 }
485fccd5
BA
604 );
605 }
c6788ecf 606 // Send game info to everyone except opponent (and me)
5ea8d113
BA
607 const playersNames = gameInfo.players.map(p => {name: p.name});
608 Object.keys(this.people).forEach(sid => {
609 if (![this.st.user.sid,target].includes(sid))
610 {
611 this.st.conn.send(JSON.stringify({code:"game",
612 game: { //minimal game info:
613 id: gameInfo.id,
614 players: playersNames,
615 vid: gameInfo.vid,
616 timeControl: gameInfo.timeControl,
617 },
618 target: sid}));
619 }
620 });
fb54f098 621 },
a9b131f1 622 // NOTE: for live games only (corr games start on the server)
42c15a75 623 startNewGame: function(gameInfo) {
25996aed
BA
624 const game = Object.assign({}, gameInfo, {
625 // (other) Game infos: constant
6d01bb17 626 fenStart: gameInfo.fen,
92a523d1 627 added: Date.now(),
25996aed 628 // Game state (including FEN): will be updated
967a2686 629 moves: [],
a9b131f1 630 clocks: [-1, -1], //-1 = unstarted
66d03f23 631 initime: [0, 0], //initialized later
967a2686 632 score: "*",
a7808884 633 });
967a2686 634 GameStorage.add(game);
7b626bdd
BA
635 if (this.st.settings.sound >= 1)
636 new Audio("/sounds/newgame.mp3").play().catch(err => {});
11667c79 637 this.$router.push("/game/" + gameInfo.id);
1efe1d79 638 },
fb54f098 639 },
85e5b5c1 640};
ccd4a2b7 641</script>
85e5b5c1 642
41c80bb6 643<style lang="sass" scoped>
5bcc9b31
BA
644.active
645 color: #42a983
9ca1e26b
BA
646#newGame
647 display: block
72ccbd67 648 margin: 10px auto 5px auto
ed06d9e9
BA
649#people
650 width: 100%
651#players
652 width: 50%
653 position: relative
654 float: left
655#chat
656 width: 50%
657 float: left
658 position: relative
659@media screen and (max-width: 767px)
660 #players, #chats
661 width: 100%
72ccbd67
BA
662#chat > .card
663 max-width: 100%
664 margin: 0;
665 border: none;
41c80bb6 666#players > p
ed06d9e9 667 margin-left: 5px
dcd68c41
BA
668.anonymous
669 font-style: italic
670button.player-action
41c80bb6 671 margin-left: 32px
85e5b5c1 672</style>