Some fixes
[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 {
b1ea2149
BA
134 // NOTE: a challenge survives 3 minutes, for potential connection issues
135 if ((Date.now() - chall.added)/1000 <= 3*60)
136 {
137 chall.added = Date.now(); //update added time, for next disconnect...
f6f2bef1 138 this.challenges.push(chall);
b1ea2149
BA
139 localStorage.setItem("challenge", JSON.stringify(chall));
140 }
f6f2bef1
BA
141 else
142 localStorage.removeItem("challenge");
143 }
3d55deea
BA
144 // Ask server for current corr games (all but mines)
145 ajax(
146 "/games",
147 "GET",
148 {uid: this.st.user.id, excluded: true},
149 response => {
150 this.games = this.games.concat(response.games.map(g => {
151 const type = this.classifyObject(g);
152 const vname = this.getVname(g.vid);
153 return Object.assign({}, g, {type: type, vname: vname});
154 }));
155 }
156 );
157 // Also ask for corr challenges (open + sent to me)
158 ajax(
159 "/challenges",
160 "GET",
161 {uid: this.st.user.id},
162 response => {
163 // Gather all senders names, and then retrieve full identity:
164 // (TODO [perf]: some might be online...)
165 const uids = response.challenges.map(c => { return c.uid });
166 ajax("/users",
167 "GET",
168 { ids: uids.join(",") },
169 response2 => {
170 let names = {};
171 response2.users.forEach(u => {names[u.id] = u.name});
172 this.challenges = this.challenges.concat(
173 response.challenges.map(c => {
174 // (just players names in fact)
175 const from = {name: names[c.uid], id: c.uid};
176 const type = this.classifyObject(c);
177 const vname = this.getVname(c.vid);
178 return Object.assign({}, c, {type: type, vname: vname, from: from});
179 })
180 )
181 }
182 );
183 }
184 );
2ada153c 185 // 0.1] Ask server for room composition:
7b01e447 186 const funcPollClients = () => {
ed06d9e9
BA
187 // Same strategy as in Game.vue: send connection
188 // after we're sure WebSocket is initialized
189 this.st.conn.send(JSON.stringify({code:"connect"}));
81d9ce72 190 this.st.conn.send(JSON.stringify({code:"pollclients"}));
4d64881e 191 };
7b01e447
BA
192 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
193 funcPollClients();
194 else //socket not ready yet (initial loading)
3cb412e9 195 this.st.conn.onopen = funcPollClients;
4d64881e
BA
196 this.st.conn.onmessage = this.socketMessageListener;
197 const socketCloseListener = () => {
cdb34c93 198 store.socketCloseListener(); //reinitialize connexion (in store.js)
4d64881e
BA
199 this.st.conn.addEventListener('message', this.socketMessageListener);
200 this.st.conn.addEventListener('close', socketCloseListener);
201 };
202 this.st.conn.onclose = socketCloseListener;
9d58ef95 203 },
fb54f098 204 methods: {
a6bddfc6 205 // Helpers:
6855163c
BA
206 filterChallenges: function(type) {
207 return this.challenges.filter(c => c.type == type);
208 },
209 filterGames: function(type) {
a9b131f1 210 return this.games.filter(g => g.type == type);
6855163c 211 },
2ada153c 212 classifyObject: function(o) { //challenge or game
6855163c 213 // Heuristic: should work for most cases... (TODO)
2ada153c 214 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
6855163c 215 },
2ada153c 216 showGame: function(g) {
5bd05dba 217 // NOTE: we are an observer, since only games I don't play are shown here
2ada153c 218 // ==> Moves sent by connected remote player(s) if live game
d9b86b16 219 let url = "/game/" + g.id;
2ada153c 220 if (g.type == "live")
dc284d90 221 url += "?rid=" + g.rid;
2ada153c 222 this.$router.push(url);
a6bddfc6 223 },
5bcc9b31
BA
224 setDisplay: function(letter, type, e) {
225 this[letter + "display"] = type;
226 e.target.classList.add("active");
227 if (!!e.target.previousElementSibling)
228 e.target.previousElementSibling.classList.remove("active");
229 else
230 e.target.nextElementSibling.classList.remove("active");
231 },
a6bddfc6 232 getVname: function(vid) {
f41ce580
BA
233 const variant = this.st.variants.find(v => v.id == vid);
234 // this.st.variants might be uninitialized (variant == null)
235 return (!!variant ? variant.name : "");
a6bddfc6 236 },
dcd68c41 237 whatPlayerDoes: function(p) {
41c80bb6
BA
238 if (this.games.some(g => g.type == "live"
239 && g.players.some(pl => pl.sid == p.sid)))
240 {
dcd68c41 241 return "Playing";
41c80bb6 242 }
dcd68c41 243 return "Challenge"; //player is available
5bd05dba 244 },
a6bddfc6
BA
245 sendSomethingTo: function(to, code, obj, warnDisconnected) {
246 const doSend = (code, obj, sid) => {
247 this.st.conn.send(JSON.stringify(Object.assign(
a6bddfc6
BA
248 {code: code},
249 obj,
250 {target: sid}
251 )));
252 };
c9695cb1 253 if (!!to)
a6bddfc6 254 {
c9695cb1 255 // Challenge with targeted players
dcd68c41
BA
256 const targetSid =
257 Object.keys(this.people).find(sid => this.people[sid].name == to);
c9695cb1
BA
258 if (!targetSid)
259 {
260 if (!!warnDisconnected)
5ea8d113
BA
261 alert("Warning: " + to + " is not connected");
262 return false;
c9695cb1
BA
263 }
264 else
265 doSend(code, obj, targetSid);
a6bddfc6
BA
266 }
267 else
268 {
5ea8d113 269 // Open challenge: send to all connected players (me excepted)
dcd68c41
BA
270 Object.keys(this.people).forEach(sid => {
271 if (sid != this.st.user.sid)
272 doSend(code, obj, sid);
a6bddfc6
BA
273 });
274 }
5ea8d113 275 return true;
a6bddfc6
BA
276 },
277 // Messaging center:
9d58ef95
BA
278 socketMessageListener: function(msg) {
279 const data = JSON.parse(msg.data);
280 switch (data.code)
281 {
6d9f4315
BA
282 case "duplicate":
283 alert("Warning: duplicate 'offline' connection");
284 break;
f4f4c03c 285 // 0.2] Receive clients list (just socket IDs)
81d9ce72 286 case "pollclients":
1efe1d79 287 {
5a3da968 288 data.sockIds.forEach(sid => {
dcd68c41 289 this.$set(this.people, sid, {id:0, name:""});
81d9ce72 290 // Ask identity, challenges and game(s)
5a3da968 291 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
2ada153c 292 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
5a3da968 293 });
cd0d7743
BA
294 // Also ask current games to all playing peers (TODO: some design issue)
295 this.st.conn.send(JSON.stringify({code:"askgames"}));
5a3da968 296 break;
1efe1d79 297 }
81d9ce72 298 case "askidentity":
1efe1d79 299 {
6855163c
BA
300 // Request for identification: reply if I'm not anonymous
301 if (this.st.user.id > 0)
302 {
dcd68c41
BA
303 this.st.conn.send(JSON.stringify({code:"identity",
304 user: {
305 // NOTE: decompose to avoid revealing email
306 name: this.st.user.name,
307 sid: this.st.user.sid,
308 id: this.st.user.id,
309 },
310 target:data.from}));
6855163c 311 }
5a3da968 312 break;
1efe1d79 313 }
dcd68c41
BA
314 case "identity":
315 {
316 this.$set(this.people, data.user.sid,
317 {id: data.user.id, name: data.user.name});
318 break;
319 }
dd75774d 320 case "askchallenge":
1efe1d79 321 {
6855163c 322 // Send my current live challenge (if any)
5ea8d113
BA
323 const cIdx = this.challenges.findIndex(c =>
324 c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
325 if (cIdx >= 0)
326 {
327 const c = this.challenges[cIdx];
5ea8d113
BA
328 if (!!c.to)
329 {
330 // Only share targeted challenges to the targets:
331 const toSid = Object.keys(this.people).find(k =>
332 this.people[k].name == c.to);
333 if (toSid != data.from)
334 return;
335 }
dd75774d
BA
336 const myChallenge =
337 {
81d9ce72 338 // Minimal challenge informations: (from not required)
2ada153c 339 id: c.id,
81d9ce72
BA
340 to: c.to,
341 fen: c.fen,
342 vid: c.vid,
5ea8d113 343 timeControl: c.timeControl,
dd75774d
BA
344 };
345 this.st.conn.send(JSON.stringify({code:"challenge",
42c15a75 346 chall:myChallenge, target:data.from}));
81d9ce72
BA
347 }
348 break;
1efe1d79 349 }
dd75774d 350 case "challenge":
1efe1d79 351 {
dd75774d 352 // Receive challenge from some player (+sid)
6855163c 353 let newChall = data.chall;
2ada153c 354 newChall.type = this.classifyObject(data.chall);
dcd68c41
BA
355 newChall.from =
356 Object.assign({sid:data.from}, this.people[data.from]);
42c15a75 357 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
25996aed 358 newChall.vname = this.getVname(newChall.vid);
6855163c 359 this.challenges.push(newChall);
81d9ce72 360 break;
1efe1d79 361 }
dd75774d 362 case "game":
1efe1d79 363 {
6855163c 364 // Receive game from some player (+sid)
6855163c 365 // NOTE: it may be correspondance (if newgame while we are connected)
b1ea2149
BA
366 // If duplicate found: select rid (remote ID) at random
367 let game = this.games.find(g => g.id == data.game.id);
368 if (!!game && Math.random() < 0.5)
369 game.rid = data.from;
370 else
d9b86b16
BA
371 {
372 let newGame = data.game;
373 newGame.type = this.classifyObject(data.game);
a9b131f1 374 newGame.vname = this.getVname(data.game.vid);
d9b86b16
BA
375 newGame.rid = data.from;
376 newGame.score = "*";
377 this.games.push(newGame);
378 }
81d9ce72 379 break;
1efe1d79 380 }
9d58ef95 381 case "newgame":
1efe1d79 382 {
66d03f23
BA
383 // TODO: next line required ?!
384 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
5d04793e 385 // New game just started: data contain all information
66d03f23 386 if (this.classifyObject(data.gameInfo) == "live")
5d04793e 387 this.startNewGame(data.gameInfo);
5d04793e
BA
388 else
389 {
3d55deea 390 this.infoMessage = "New game started: " +
11667c79
BA
391 "<a href='#/game/" + data.gameInfo.id + "'>" +
392 "#/game/" + data.gameInfo.id + "</a>";
dce792f6
BA
393 let modalBox = document.getElementById("modalInfo");
394 modalBox.checked = true;
3d55deea 395 setTimeout(() => { modalBox.checked = false; }, 3000);
5d04793e 396 }
9d58ef95 397 break;
1efe1d79 398 }
bb7dd7db
BA
399 case "refusechallenge":
400 {
5bd05dba 401 ArrayFun.remove(this.challenges, c => c.id == data.cid);
b1ea2149 402 localStorage.removeItem("challenge");
5ea8d113 403 alert(this.people[data.from].name + " declined your challenge");
bb7dd7db
BA
404 break;
405 }
1efe1d79
BA
406 case "deletechallenge":
407 {
1ba761c8 408 // NOTE: the challenge may be already removed
9d58ef95 409 ArrayFun.remove(this.challenges, c => c.id == data.cid);
66d03f23 410 localStorage.removeItem("challenge"); //in case of
9d58ef95 411 break;
1efe1d79 412 }
b4d619d1 413 case "connect":
1efe1d79 414 {
dcd68c41 415 this.$set(this.people, data.from, {name:"", id:0});
c6788ecf
BA
416 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
417 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
418 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
9d58ef95 419 break;
1efe1d79 420 }
b4d619d1 421 case "disconnect":
1efe1d79 422 {
dcd68c41 423 this.$delete(this.people, data.from);
a6bddfc6 424 // Also remove all challenges sent by this player:
c6788ecf 425 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
2ada153c
BA
426 // And all live games where he plays and no other opponent is online
427 ArrayFun.remove(this.games, g =>
c6788ecf 428 g.type == "live" && (g.players.every(p => p.sid == data.from
dcd68c41 429 || !this.people[p.sid])), "all");
9d58ef95 430 break;
1efe1d79 431 }
9d58ef95
BA
432 }
433 },
a6bddfc6 434 // Challenge lifecycle:
b4d619d1
BA
435 tryChallenge: function(player) {
436 if (player.id == 0)
437 return; //anonymous players cannot be challenged
a7808884 438 this.newchallenge.to = player.name;
b4d619d1 439 doClick("modalNewgame");
fb54f098 440 },
dcd68c41
BA
441 challOrWatch: function(p, e) {
442 switch (e.target.innerHTML)
443 {
444 case "Challenge":
445 this.tryChallenge(p);
446 break;
447 case "Playing":
448 // NOTE: this search for game was already done for rendering
449 this.showGame(this.games.find(
41c80bb6 450 g => g.type=="live" && g.players.some(pl => pl.sid == p.sid)));
dcd68c41
BA
451 break;
452 };
453 },
9d58ef95 454 newChallenge: async function() {
bb7dd7db 455 const vname = this.getVname(this.newchallenge.vid);
1efe1d79
BA
456 const vModule = await import("@/variants/" + vname + ".js");
457 window.V = vModule.VariantRules;
dcd68c41
BA
458 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
459 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
9d58ef95
BA
460 const error = checkChallenge(this.newchallenge);
461 if (!!error)
462 return alert(error);
2ada153c 463 const ctype = this.classifyObject(this.newchallenge);
098cd7f1
BA
464 if (ctype == "corr" && this.st.user.id <= 0)
465 return alert("Please log in to play correspondance games");
bb7dd7db 466 // NOTE: "from" information is not required here
a7808884 467 let chall = Object.assign({}, this.newchallenge);
2ada153c 468 const finishAddChallenge = (cid,warnDisconnected) => {
1efe1d79 469 chall.id = cid || "c" + getRandString();
2ada153c 470 // Send challenge to peers (if connected)
5ea8d113
BA
471 const isSent = this.sendSomethingTo(chall.to, "challenge",
472 {chall:chall}, !!warnDisconnected);
473 if (!isSent)
474 return;
475 // Remove old challenge if any (only one at a time):
476 const cIdx = this.challenges.findIndex(c =>
477 c.from.sid == this.st.user.sid && c.type == ctype);
478 if (cIdx >= 0)
479 {
480 // Delete current challenge (will be replaced now)
481 this.sendSomethingTo(this.challenges[cIdx].to,
482 "deletechallenge", {cid:this.challenges[cIdx].id});
483 if (ctype == "corr")
484 {
485 ajax(
486 "/challenges",
487 "DELETE",
488 {id: this.challenges[cIdx].id}
489 );
490 }
491 this.challenges.splice(cIdx, 1);
492 }
493 // Add new challenge:
1efe1d79 494 chall.added = Date.now();
a9b131f1 495 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
bb7dd7db
BA
496 chall.type = ctype;
497 chall.vname = vname;
dcd68c41
BA
498 chall.from = { //decompose to avoid revealing email
499 sid: this.st.user.sid,
500 id: this.st.user.id,
501 name: this.st.user.name,
502 };
1efe1d79 503 this.challenges.push(chall);
f41ce580
BA
504 if (ctype == "live")
505 localStorage.setItem("challenge", JSON.stringify(chall));
b4d619d1
BA
506 document.getElementById("modalNewgame").checked = false;
507 };
1efe1d79
BA
508 if (ctype == "live")
509 {
510 // Live challenges have a random ID
2ada153c 511 finishAddChallenge(null, "warnDisconnected");
03608482 512 }
b4d619d1 513 else
03608482 514 {
b4d619d1 515 // Correspondance game: send challenge to server
03608482 516 ajax(
1efe1d79 517 "/challenges",
03608482 518 "POST",
bebcc8d4 519 { chall: chall },
1efe1d79 520 response => { finishAddChallenge(response.cid); }
03608482 521 );
9d58ef95 522 }
fb54f098 523 },
a6bddfc6 524 clickChallenge: function(c) {
485fccd5
BA
525 const myChallenge = (c.from.sid == this.st.user.sid //live
526 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
527 if (!myChallenge)
a6bddfc6 528 {
3d55deea
BA
529 if (c.type == "corr" && this.st.user.id <= 0)
530 return alert("Please log in to accept corr challenges");
a6bddfc6 531 c.accepted = true;
485fccd5 532 if (!!c.to) //c.to == this.st.user.name (connected)
a6bddfc6
BA
533 {
534 // TODO: if special FEN, show diagram after loading variant
535 c.accepted = confirm("Accept challenge?");
536 }
485fccd5 537 if (c.accepted)
36093eba 538 {
dcd68c41
BA
539 c.seat = { //again, avoid c.seat = st.user to not reveal email
540 sid: this.st.user.sid,
541 id: this.st.user.id,
542 name: this.st.user.name,
543 };
485fccd5
BA
544 this.launchGame(c);
545 }
546 else
547 {
548 this.st.conn.send(JSON.stringify({
549 code: "refusechallenge",
550 cid: c.id, target: c.from.sid}));
36093eba 551 }
b1ea2149
BA
552 // TODO: refactor the "sendSomethingTo()" function
553 if (!c.to)
554 this.sendSomethingTo(null, "deletechallenge", {cid:c.id});
555 else
556 {
557 this.st.conn.send(JSON.stringify({
558 code:"deletechallenge", target: c.from.sid, cid: c.id}));
559 }
a6bddfc6 560 }
2be5d614 561 else //my challenge
485fccd5 562 {
2be5d614
BA
563 if (c.type == "corr")
564 {
565 ajax(
566 "/challenges",
567 "DELETE",
568 {id: c.id}
569 );
570 }
f41ce580
BA
571 else //live
572 localStorage.removeItem("challenge");
5ea8d113 573 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
485fccd5 574 }
5ea8d113 575 // In all cases, the challenge is consumed:
3d55deea 576 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
a6bddfc6 577 },
485fccd5 578 // NOTE: when launching game, the challenge is already deleted
36093eba 579 launchGame: async function(c) {
a9b131f1 580 const vModule = await import("@/variants/" + c.vname + ".js");
a6bddfc6 581 window.V = vModule.VariantRules;
4b0384fa
BA
582 // These game informations will be sent to other players
583 const gameInfo =
a6bddfc6 584 {
11667c79 585 id: getRandString(),
a6bddfc6 586 fen: c.fen || V.GenRandInitFen(),
5d04793e 587 players: shuffle([c.from, c.seat]), //white then black
a6bddfc6 588 vid: c.vid,
f41ce580 589 vname: c.vname, //theoretically vid is enough, but much easier with vname
a9b131f1 590 timeControl: c.timeControl,
a6bddfc6 591 };
5ea8d113
BA
592 let oppsid = c.from.sid; //may not be defined if corr + offline opp
593 if (!oppsid)
8c564f46 594 {
5ea8d113 595 oppsid = Object.keys(this.people).find(sid =>
dcd68c41 596 this.people[sid].id == c.from.id);
8c564f46 597 }
411d23cd 598 const tryNotifyOpponent = () => {
5ea8d113 599 if (!!oppsid) //opponent is online
411d23cd
BA
600 {
601 this.st.conn.send(JSON.stringify({code:"newgame",
5ea8d113 602 gameInfo:gameInfo, target:oppsid, cid:c.id}));
411d23cd
BA
603 }
604 };
485fccd5 605 if (c.type == "live")
411d23cd 606 {
b1ea2149 607 // NOTE: in this case we are sure opponent is online
411d23cd 608 tryNotifyOpponent();
485fccd5 609 this.startNewGame(gameInfo);
411d23cd 610 }
485fccd5
BA
611 else //corr: game only on server
612 {
613 ajax(
614 "/games",
615 "POST",
2be5d614 616 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
411d23cd 617 response => {
11667c79 618 gameInfo.id = response.gameId;
411d23cd
BA
619 tryNotifyOpponent();
620 this.$router.push("/game/" + response.gameId);
621 }
485fccd5
BA
622 );
623 }
c6788ecf 624 // Send game info to everyone except opponent (and me)
5ea8d113 625 Object.keys(this.people).forEach(sid => {
b1ea2149 626 if (![this.st.user.sid,oppsid].includes(sid))
5ea8d113
BA
627 {
628 this.st.conn.send(JSON.stringify({code:"game",
629 game: { //minimal game info:
630 id: gameInfo.id,
b1ea2149 631 players: gameInfo.players,
5ea8d113
BA
632 vid: gameInfo.vid,
633 timeControl: gameInfo.timeControl,
634 },
635 target: sid}));
636 }
637 });
fb54f098 638 },
a9b131f1 639 // NOTE: for live games only (corr games start on the server)
42c15a75 640 startNewGame: function(gameInfo) {
25996aed
BA
641 const game = Object.assign({}, gameInfo, {
642 // (other) Game infos: constant
6d01bb17 643 fenStart: gameInfo.fen,
92a523d1 644 added: Date.now(),
25996aed 645 // Game state (including FEN): will be updated
967a2686 646 moves: [],
a9b131f1 647 clocks: [-1, -1], //-1 = unstarted
66d03f23 648 initime: [0, 0], //initialized later
967a2686 649 score: "*",
a7808884 650 });
967a2686 651 GameStorage.add(game);
7b626bdd
BA
652 if (this.st.settings.sound >= 1)
653 new Audio("/sounds/newgame.mp3").play().catch(err => {});
11667c79 654 this.$router.push("/game/" + gameInfo.id);
1efe1d79 655 },
fb54f098 656 },
85e5b5c1 657};
ccd4a2b7 658</script>
85e5b5c1 659
41c80bb6 660<style lang="sass" scoped>
5bcc9b31
BA
661.active
662 color: #42a983
9ca1e26b
BA
663#newGame
664 display: block
72ccbd67 665 margin: 10px auto 5px auto
ed06d9e9
BA
666#people
667 width: 100%
668#players
669 width: 50%
670 position: relative
671 float: left
672#chat
673 width: 50%
674 float: left
675 position: relative
676@media screen and (max-width: 767px)
677 #players, #chats
678 width: 100%
72ccbd67
BA
679#chat > .card
680 max-width: 100%
681 margin: 0;
682 border: none;
41c80bb6 683#players > p
ed06d9e9 684 margin-left: 5px
dcd68c41
BA
685.anonymous
686 font-style: italic
687button.player-action
41c80bb6 688 margin-left: 32px
85e5b5c1 689</style>