Fix attempt - still chat issues when tabs are not reloaded after live game start
[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
BA
9 input#modalNewgame.modal(type="checkbox")
10 div(role="dialog" aria-labelledby="titleFenedit")
11 .card.smallpad
12 label#closeNewgame.modal-close(for="modalNewgame")
13 fieldset
14 label(for="selectVariant") {{ st.tr["Variant"] }}
9d58ef95 15 select#selectVariant(v-model="newchallenge.vid")
85e5b5c1 16 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
5b020e73 17 fieldset
b4d619d1 18 label(for="timeControl") {{ st.tr["Time control"] }}
9d58ef95 19 input#timeControl(type="text" v-model="newchallenge.timeControl"
b4d619d1
BA
20 placeholder="3m+2s, 1h+30s, 7d+1d ...")
21 fieldset(v-if="st.user.id > 0")
9d58ef95 22 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
6fba6e0c 23 input#selectPlayers(type="text" v-model="newchallenge.to")
b4d619d1 24 fieldset(v-if="st.user.id > 0")
9d58ef95
BA
25 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
26 input#inputFen(type="text" v-model="newchallenge.fen")
b4d619d1 27 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
9d58ef95
BA
28 .row
29 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
30 button(onClick="doClick('modalNewgame')") New game
31 .row
1efe1d79 32 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
6855163c
BA
33 .collapse
34 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
35 label(for="challengeSection" aria-hidden="true") Challenges
36 div
37 .button-group
38 button(@click="cdisplay='live'") Live Challenges
39 button(@click="cdisplay='corr'") 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")
1efe1d79 44 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
6855163c
BA
45 label(for="peopleSection" aria-hidden="true") People
46 div
1efe1d79
BA
47 .button-group
48 button(@click="pdisplay='players'") Players
49 button(@click="pdisplay='chat'") Chat
6855163c
BA
50 #players(v-show="pdisplay=='players'")
51 h3 Online players
52 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
53 :class="{anonymous: !!p.count}"
54 )
55 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
56 #chat(v-show="pdisplay=='chat'")
57 h3 Chat (TODO)
1efe1d79 58 input#gameSection(type="radio" aria-hidden="true" name="accordion")
6855163c
BA
59 label(for="gameSection" aria-hidden="true") Games
60 div
61 .button-group
62 button(@click="gdisplay='live'") Live games
63 button(@click="gdisplay='corr'") 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";
5b020e73
BA
76import GameList from "@/components/GameList.vue";
77import ChallengeList from "@/components/ChallengeList.vue";
967a2686 78import { GameStorage } from "@/utils/gameStorage";
625022fd 79export default {
cf2343ce 80 name: "my-hall",
5b020e73
BA
81 components: {
82 GameList,
83 ChallengeList,
84 },
fb54f098
BA
85 data: function () {
86 return {
5b020e73 87 st: store.state,
6855163c
BA
88 cdisplay: "live", //or corr
89 pdisplay: "players", //or chat
fb54f098 90 gdisplay: "live",
6855163c 91 games: [],
b4d619d1 92 challenges: [],
92a523d1 93 people: [], //people in main hall
3d55deea 94 infoMessage: "",
9d58ef95 95 newchallenge: {
fb54f098
BA
96 fen: "",
97 vid: 0,
6fba6e0c 98 to: "", //name of challenged player (if any)
6faa92f2 99 timeControl: "", //"2m+2s" ...etc
fb54f098
BA
100 },
101 };
102 },
fd7aea36
BA
103 watch: {
104 // st.variants changes only once, at loading from [] to [...]
105 "st.variants": function(variantArray) {
106 // Set potential challenges and games variant names:
107 this.challenges.forEach(c => {
108 if (c.vname == "")
109 c.vname = this.getVname(c.vid);
110 });
111 this.games.forEach(g => {
112 if (g.vname == "")
f41ce580 113 g.vname = this.getVname(g.vid);
fd7aea36
BA
114 });
115 },
116 },
b4d619d1
BA
117 computed: {
118 uniquePlayers: function() {
6855163c 119 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
bcaa8c00
BA
120 let anonymous = {name:"@nonymous", count:0};
121 let playerList = {};
6fba6e0c 122 this.people.forEach(p => {
b4d619d1 123 if (p.id > 0)
bcaa8c00
BA
124 {
125 // We don't count registered users connections: either they are here or not.
126 if (!playerList[p.id])
127 playerList[p.id] = {name: p.name, count: 0};
128 }
b4d619d1 129 else
4d64881e 130 anonymous.count++;
b4d619d1 131 });
4d64881e 132 if (anonymous.count > 0)
bcaa8c00
BA
133 playerList[0] = anonymous;
134 return Object.values(playerList);
b4d619d1
BA
135 },
136 },
9d58ef95 137 created: function() {
4d64881e 138 // Always add myself to players' list
66d03f23
BA
139 const my = this.st.user;
140 this.people.push({sid:my.sid, id:my.id, name:my.name});
f6f2bef1
BA
141 // Retrieve live challenge (not older than 30 minute) if any:
142 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
143 if (!!chall)
144 {
145 if ((Date.now() - chall.added)/1000 <= 30*60)
146 this.challenges.push(chall);
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 = () => {
81d9ce72 193 this.st.conn.send(JSON.stringify({code:"pollclients"}));
4d64881e 194 };
7b01e447
BA
195 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
196 funcPollClients();
197 else //socket not ready yet (initial loading)
3cb412e9 198 this.st.conn.onopen = funcPollClients;
4d64881e
BA
199 this.st.conn.onmessage = this.socketMessageListener;
200 const socketCloseListener = () => {
cdb34c93 201 store.socketCloseListener(); //reinitialize connexion (in store.js)
4d64881e
BA
202 this.st.conn.addEventListener('message', this.socketMessageListener);
203 this.st.conn.addEventListener('close', socketCloseListener);
204 };
205 this.st.conn.onclose = socketCloseListener;
9d58ef95 206 },
fb54f098 207 methods: {
a6bddfc6 208 // Helpers:
6855163c
BA
209 filterChallenges: function(type) {
210 return this.challenges.filter(c => c.type == type);
211 },
212 filterGames: function(type) {
a9b131f1 213 return this.games.filter(g => g.type == type);
6855163c 214 },
2ada153c 215 classifyObject: function(o) { //challenge or game
6855163c 216 // Heuristic: should work for most cases... (TODO)
2ada153c 217 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
6855163c 218 },
2ada153c 219 showGame: function(g) {
5bd05dba 220 // NOTE: we are an observer, since only games I don't play are shown here
2ada153c 221 // ==> Moves sent by connected remote player(s) if live game
d9b86b16 222 let url = "/game/" + g.id;
2ada153c
BA
223 if (g.type == "live")
224 {
d9b86b16
BA
225 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
226 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
227 url += "?rid=" + remotes[rIdx].sid;
2ada153c
BA
228 }
229 this.$router.push(url);
a6bddfc6
BA
230 },
231 getVname: function(vid) {
f41ce580
BA
232 const variant = this.st.variants.find(v => v.id == vid);
233 // this.st.variants might be uninitialized (variant == null)
234 return (!!variant ? variant.name : "");
a6bddfc6
BA
235 },
236 getSid: function(pname) {
6fba6e0c
BA
237 const pIdx = this.people.findIndex(pl => pl.name == pname);
238 return (pIdx === -1 ? null : this.people[pIdx].sid);
a6bddfc6 239 },
5bd05dba 240 getPname: function(sid) {
6fba6e0c
BA
241 const pIdx = this.people.findIndex(pl => pl.sid == sid);
242 return (pIdx === -1 ? null : this.people[pIdx].name);
5bd05dba 243 },
a6bddfc6
BA
244 sendSomethingTo: function(to, code, obj, warnDisconnected) {
245 const doSend = (code, obj, sid) => {
246 this.st.conn.send(JSON.stringify(Object.assign(
247 {},
248 {code: code},
249 obj,
250 {target: sid}
251 )));
252 };
c9695cb1 253 if (!!to)
a6bddfc6 254 {
c9695cb1
BA
255 // Challenge with targeted players
256 const targetSid = this.getSid(to);
257 if (!targetSid)
258 {
259 if (!!warnDisconnected)
260 alert("Warning: " + pname + " is not connected");
261 }
262 else
263 doSend(code, obj, targetSid);
a6bddfc6
BA
264 }
265 else
266 {
267 // Open challenge: send to all connected players (except us)
6fba6e0c 268 this.people.forEach(p => {
a6bddfc6
BA
269 if (p.sid != this.st.user.sid) //only sid is always set
270 doSend(code, obj, p.sid);
271 });
272 }
273 },
274 // Messaging center:
9d58ef95
BA
275 socketMessageListener: function(msg) {
276 const data = JSON.parse(msg.data);
277 switch (data.code)
278 {
f4f4c03c 279 // 0.2] Receive clients list (just socket IDs)
81d9ce72 280 case "pollclients":
1efe1d79 281 {
5a3da968 282 data.sockIds.forEach(sid => {
6fba6e0c 283 this.people.push({sid: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 {
297 this.st.conn.send(JSON.stringify(
66d03f23
BA
298 // people[0] instead of st.user to avoid sending email
299 {code:"identity", user:this.people[0], target:data.from}));
6855163c 300 }
5a3da968 301 break;
1efe1d79 302 }
dd75774d 303 case "askchallenge":
1efe1d79 304 {
6855163c 305 // Send my current live challenge (if any)
dd75774d 306 const cIdx = this.challenges
6855163c 307 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
308 if (cIdx >= 0)
309 {
310 const c = this.challenges[cIdx];
311 const myChallenge =
312 {
81d9ce72 313 // Minimal challenge informations: (from not required)
2ada153c 314 id: c.id,
81d9ce72
BA
315 to: c.to,
316 fen: c.fen,
317 vid: c.vid,
318 timeControl: c.timeControl
dd75774d
BA
319 };
320 this.st.conn.send(JSON.stringify({code:"challenge",
42c15a75 321 chall:myChallenge, target:data.from}));
81d9ce72
BA
322 }
323 break;
1efe1d79 324 }
5a3da968 325 case "identity":
1efe1d79 326 {
6fba6e0c
BA
327 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
328 this.people[pIdx].id = data.user.id;
329 this.people[pIdx].name = data.user.name;
5a3da968 330 break;
1efe1d79 331 }
dd75774d 332 case "challenge":
1efe1d79 333 {
dd75774d 334 // Receive challenge from some player (+sid)
6855163c 335 let newChall = data.chall;
2ada153c 336 newChall.type = this.classifyObject(data.chall);
6fba6e0c
BA
337 const pIdx = this.people.findIndex(p => p.sid == data.from);
338 newChall.from = this.people[pIdx]; //may be anonymous
42c15a75 339 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
25996aed 340 newChall.vname = this.getVname(newChall.vid);
6855163c 341 this.challenges.push(newChall);
81d9ce72 342 break;
1efe1d79 343 }
dd75774d 344 case "game":
1efe1d79 345 {
6855163c 346 // Receive game from some player (+sid)
6855163c 347 // NOTE: it may be correspondance (if newgame while we are connected)
d9b86b16
BA
348 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
349 {
350 let newGame = data.game;
351 newGame.type = this.classifyObject(data.game);
a9b131f1 352 newGame.vname = this.getVname(data.game.vid);
d9b86b16
BA
353 newGame.rid = data.from;
354 newGame.score = "*";
355 this.games.push(newGame);
356 }
81d9ce72 357 break;
1efe1d79 358 }
9d58ef95 359 case "newgame":
1efe1d79 360 {
66d03f23
BA
361 // TODO: next line required ?!
362 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
5d04793e 363 // New game just started: data contain all information
66d03f23 364 if (this.classifyObject(data.gameInfo) == "live")
5d04793e 365 this.startNewGame(data.gameInfo);
5d04793e
BA
366 else
367 {
3d55deea 368 this.infoMessage = "New game started: " +
11667c79
BA
369 "<a href='#/game/" + data.gameInfo.id + "'>" +
370 "#/game/" + data.gameInfo.id + "</a>";
dce792f6
BA
371 let modalBox = document.getElementById("modalInfo");
372 modalBox.checked = true;
3d55deea 373 setTimeout(() => { modalBox.checked = false; }, 3000);
5d04793e 374 }
9d58ef95 375 break;
1efe1d79 376 }
bb7dd7db
BA
377 case "refusechallenge":
378 {
485fccd5 379 alert(this.getPname(data.from) + " declined your challenge");
5bd05dba 380 ArrayFun.remove(this.challenges, c => c.id == data.cid);
bb7dd7db
BA
381 break;
382 }
1efe1d79
BA
383 case "deletechallenge":
384 {
1ba761c8 385 // NOTE: the challenge may be already removed
9d58ef95 386 ArrayFun.remove(this.challenges, c => c.id == data.cid);
66d03f23 387 localStorage.removeItem("challenge"); //in case of
9d58ef95 388 break;
1efe1d79 389 }
b4d619d1 390 case "connect":
1efe1d79 391 {
c6788ecf
BA
392 this.people.push({name:"", id:0, sid:data.from});
393 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
394 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
395 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
9d58ef95 396 break;
1efe1d79 397 }
b4d619d1 398 case "disconnect":
1efe1d79 399 {
c6788ecf 400 ArrayFun.remove(this.people, p => p.sid == data.from);
a6bddfc6 401 // Also remove all challenges sent by this player:
c6788ecf 402 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
2ada153c
BA
403 // And all live games where he plays and no other opponent is online
404 ArrayFun.remove(this.games, g =>
c6788ecf 405 g.type == "live" && (g.players.every(p => p.sid == data.from
6fba6e0c 406 || !this.people.some(pl => pl.sid == p.sid))), "all");
9d58ef95 407 break;
1efe1d79 408 }
9d58ef95
BA
409 }
410 },
a6bddfc6 411 // Challenge lifecycle:
b4d619d1
BA
412 tryChallenge: function(player) {
413 if (player.id == 0)
414 return; //anonymous players cannot be challenged
a7808884 415 this.newchallenge.to = player.name;
b4d619d1 416 doClick("modalNewgame");
fb54f098 417 },
9d58ef95 418 newChallenge: async function() {
bb7dd7db 419 const vname = this.getVname(this.newchallenge.vid);
1efe1d79
BA
420 const vModule = await import("@/variants/" + vname + ".js");
421 window.V = vModule.VariantRules;
9d58ef95
BA
422 const error = checkChallenge(this.newchallenge);
423 if (!!error)
424 return alert(error);
2ada153c 425 const ctype = this.classifyObject(this.newchallenge);
098cd7f1
BA
426 if (ctype == "corr" && this.st.user.id <= 0)
427 return alert("Please log in to play correspondance games");
bb7dd7db 428 // NOTE: "from" information is not required here
a7808884 429 let chall = Object.assign({}, this.newchallenge);
2ada153c 430 const finishAddChallenge = (cid,warnDisconnected) => {
1efe1d79 431 chall.id = cid || "c" + getRandString();
2ada153c 432 // Send challenge to peers (if connected)
c9695cb1 433 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
1efe1d79 434 chall.added = Date.now();
a9b131f1 435 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
bb7dd7db
BA
436 chall.type = ctype;
437 chall.vname = vname;
66d03f23 438 chall.from = this.people[0]; //avoid sending email
1efe1d79 439 this.challenges.push(chall);
f41ce580
BA
440 if (ctype == "live")
441 localStorage.setItem("challenge", JSON.stringify(chall));
b4d619d1
BA
442 document.getElementById("modalNewgame").checked = false;
443 };
1efe1d79
BA
444 const cIdx = this.challenges.findIndex(
445 c => c.from.sid == this.st.user.sid && c.type == ctype);
446 if (cIdx >= 0)
b4d619d1 447 {
1efe1d79 448 // Delete current challenge (will be replaced now)
bb7dd7db 449 this.sendSomethingTo(this.challenges[cIdx].to,
1efe1d79
BA
450 "deletechallenge", {cid:this.challenges[cIdx].id});
451 if (ctype == "corr")
452 {
453 ajax(
454 "/challenges",
455 "DELETE",
456 {id: this.challenges[cIdx].id}
457 );
458 }
459 this.challenges.splice(cIdx, 1);
460 }
461 if (ctype == "live")
462 {
463 // Live challenges have a random ID
2ada153c 464 finishAddChallenge(null, "warnDisconnected");
03608482 465 }
b4d619d1 466 else
03608482 467 {
b4d619d1 468 // Correspondance game: send challenge to server
03608482 469 ajax(
1efe1d79 470 "/challenges",
03608482 471 "POST",
bebcc8d4 472 { chall: chall },
1efe1d79 473 response => { finishAddChallenge(response.cid); }
03608482 474 );
9d58ef95 475 }
fb54f098 476 },
a6bddfc6 477 clickChallenge: function(c) {
485fccd5
BA
478 const myChallenge = (c.from.sid == this.st.user.sid //live
479 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
480 if (!myChallenge)
a6bddfc6 481 {
3d55deea
BA
482 if (c.type == "corr" && this.st.user.id <= 0)
483 return alert("Please log in to accept corr challenges");
a6bddfc6 484 c.accepted = true;
485fccd5 485 if (!!c.to) //c.to == this.st.user.name (connected)
a6bddfc6
BA
486 {
487 // TODO: if special FEN, show diagram after loading variant
488 c.accepted = confirm("Accept challenge?");
489 }
485fccd5 490 if (c.accepted)
36093eba 491 {
8c564f46 492 c.seat = this.people[0]; //== this.st.user, avoid revealing email
485fccd5
BA
493 this.launchGame(c);
494 }
495 else
496 {
497 this.st.conn.send(JSON.stringify({
498 code: "refusechallenge",
499 cid: c.id, target: c.from.sid}));
36093eba 500 }
a6bddfc6 501 }
2be5d614 502 else //my challenge
485fccd5 503 {
2be5d614
BA
504 if (c.type == "corr")
505 {
506 ajax(
507 "/challenges",
508 "DELETE",
509 {id: c.id}
510 );
511 }
f41ce580
BA
512 else //live
513 localStorage.removeItem("challenge");
485fccd5 514 }
3d55deea
BA
515 // In (almost) all cases, the challenge is consumed:
516 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
517 // NOTE: deletechallenge event might be redundant (but it's easier this way)
518 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
a6bddfc6 519 },
485fccd5 520 // NOTE: when launching game, the challenge is already deleted
36093eba 521 launchGame: async function(c) {
a9b131f1 522 const vModule = await import("@/variants/" + c.vname + ".js");
a6bddfc6 523 window.V = vModule.VariantRules;
4b0384fa
BA
524 // These game informations will be sent to other players
525 const gameInfo =
a6bddfc6 526 {
11667c79 527 id: getRandString(),
a6bddfc6 528 fen: c.fen || V.GenRandInitFen(),
5d04793e 529 players: shuffle([c.from, c.seat]), //white then black
a6bddfc6 530 vid: c.vid,
f41ce580 531 vname: c.vname, //theoretically vid is enough, but much easier with vname
a9b131f1 532 timeControl: c.timeControl,
a6bddfc6 533 };
8c564f46
BA
534 let target = c.from.sid; //may not be defined if corr + offline opp
535 if (!target)
536 {
537 const opponent = this.people.find(p => p.id == c.from.id);
538 if (!!opponent)
539 target = opponent.sid
540 }
411d23cd
BA
541 const tryNotifyOpponent = () => {
542 if (!!target) //opponent is online
543 {
544 this.st.conn.send(JSON.stringify({code:"newgame",
545 gameInfo:gameInfo, target:target, cid:c.id}));
546 }
547 };
485fccd5 548 if (c.type == "live")
411d23cd
BA
549 {
550 tryNotifyOpponent();
485fccd5 551 this.startNewGame(gameInfo);
411d23cd 552 }
485fccd5
BA
553 else //corr: game only on server
554 {
555 ajax(
556 "/games",
557 "POST",
2be5d614 558 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
411d23cd 559 response => {
11667c79 560 gameInfo.id = response.gameId;
411d23cd
BA
561 tryNotifyOpponent();
562 this.$router.push("/game/" + response.gameId);
563 }
485fccd5
BA
564 );
565 }
c6788ecf
BA
566 // Send game info to everyone except opponent (and me)
567 this.st.conn.send(JSON.stringify({code:"game",
568 game: { //minimal game info:
569 id: gameInfo.id,
570 players: gameInfo.players.map(p => p.name),
571 vid: gameInfo.vid,
572 timeControl: gameInfo.timeControl,
573 },
574 oppsid: target}));
fb54f098 575 },
a9b131f1 576 // NOTE: for live games only (corr games start on the server)
42c15a75 577 startNewGame: function(gameInfo) {
25996aed
BA
578 const game = Object.assign({}, gameInfo, {
579 // (other) Game infos: constant
6d01bb17 580 fenStart: gameInfo.fen,
92a523d1 581 added: Date.now(),
25996aed 582 // Game state (including FEN): will be updated
967a2686 583 moves: [],
a9b131f1 584 clocks: [-1, -1], //-1 = unstarted
66d03f23 585 initime: [0, 0], //initialized later
967a2686 586 score: "*",
a7808884 587 });
967a2686 588 GameStorage.add(game);
7b626bdd
BA
589 if (this.st.settings.sound >= 1)
590 new Audio("/sounds/newgame.mp3").play().catch(err => {});
11667c79 591 this.$router.push("/game/" + gameInfo.id);
1efe1d79 592 },
fb54f098 593 },
85e5b5c1 594};
ccd4a2b7 595</script>
85e5b5c1
BA
596
597<style lang="sass">
598// TODO
599</style>