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