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