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