socket rooms correspnding to pages. TODO: Hall+Game (split live and corr? shared...
[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 == "")
113 g.vname = this.getVname(g.vid)
114 });
115 },
116 },
b4d619d1
BA
117 computed: {
118 uniquePlayers: function() {
6855163c 119 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
4d64881e
BA
120 let anonymous = {id:0, name:"@nonymous", count:0};
121 let playerList = [];
6fba6e0c 122 this.people.forEach(p => {
b4d619d1
BA
123 if (p.id > 0)
124 playerList.push(p);
125 else
4d64881e 126 anonymous.count++;
b4d619d1 127 });
4d64881e
BA
128 if (anonymous.count > 0)
129 playerList.push(anonymous);
b4d619d1
BA
130 return playerList;
131 },
132 },
9d58ef95 133 created: function() {
4d64881e 134 // Always add myself to players' list
66d03f23
BA
135 const my = this.st.user;
136 this.people.push({sid:my.sid, id:my.id, name:my.name});
f6f2bef1
BA
137 // Retrieve live challenge (not older than 30 minute) if any:
138 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
139 if (!!chall)
140 {
141 if ((Date.now() - chall.added)/1000 <= 30*60)
142 this.challenges.push(chall);
143 else
144 localStorage.removeItem("challenge");
145 }
3d55deea
BA
146 // Ask server for current corr games (all but mines)
147 ajax(
148 "/games",
149 "GET",
150 {uid: this.st.user.id, excluded: true},
151 response => {
152 this.games = this.games.concat(response.games.map(g => {
153 const type = this.classifyObject(g);
154 const vname = this.getVname(g.vid);
155 return Object.assign({}, g, {type: type, vname: vname});
156 }));
157 }
158 );
159 // Also ask for corr challenges (open + sent to me)
160 ajax(
161 "/challenges",
162 "GET",
163 {uid: this.st.user.id},
164 response => {
165 // Gather all senders names, and then retrieve full identity:
166 // (TODO [perf]: some might be online...)
167 const uids = response.challenges.map(c => { return c.uid });
168 ajax("/users",
169 "GET",
170 { ids: uids.join(",") },
171 response2 => {
172 let names = {};
173 response2.users.forEach(u => {names[u.id] = u.name});
174 this.challenges = this.challenges.concat(
175 response.challenges.map(c => {
176 // (just players names in fact)
177 const from = {name: names[c.uid], id: c.uid};
178 const type = this.classifyObject(c);
179 const vname = this.getVname(c.vid);
180 return Object.assign({}, c, {type: type, vname: vname, from: from});
181 })
182 )
183 }
184 );
185 }
186 );
2ada153c 187 // 0.1] Ask server for room composition:
7b01e447 188 const funcPollClients = () => {
81d9ce72 189 this.st.conn.send(JSON.stringify({code:"pollclients"}));
4d64881e 190 };
7b01e447
BA
191 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
192 funcPollClients();
193 else //socket not ready yet (initial loading)
3cb412e9 194 this.st.conn.onopen = funcPollClients;
4d64881e
BA
195 this.st.conn.onmessage = this.socketMessageListener;
196 const socketCloseListener = () => {
cdb34c93 197 store.socketCloseListener(); //reinitialize connexion (in store.js)
4d64881e
BA
198 this.st.conn.addEventListener('message', this.socketMessageListener);
199 this.st.conn.addEventListener('close', socketCloseListener);
200 };
201 this.st.conn.onclose = socketCloseListener;
9d58ef95 202 },
fb54f098 203 methods: {
a6bddfc6 204 // Helpers:
6855163c
BA
205 filterChallenges: function(type) {
206 return this.challenges.filter(c => c.type == type);
207 },
208 filterGames: function(type) {
a9b131f1 209 return this.games.filter(g => g.type == type);
6855163c 210 },
2ada153c 211 classifyObject: function(o) { //challenge or game
6855163c 212 // Heuristic: should work for most cases... (TODO)
2ada153c 213 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
6855163c 214 },
2ada153c 215 showGame: function(g) {
5bd05dba 216 // NOTE: we are an observer, since only games I don't play are shown here
2ada153c 217 // ==> Moves sent by connected remote player(s) if live game
d9b86b16 218 let url = "/game/" + g.id;
2ada153c
BA
219 if (g.type == "live")
220 {
d9b86b16
BA
221 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
222 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
223 url += "?rid=" + remotes[rIdx].sid;
2ada153c
BA
224 }
225 this.$router.push(url);
a6bddfc6 226 },
a7808884 227 // TODO: ...filter(...)[0].name, one-line, just remove this function
a6bddfc6
BA
228 getVname: function(vid) {
229 const vIdx = this.st.variants.findIndex(v => v.id == vid);
ed9c9c37 230 return vIdx >= 0 ? this.st.variants[vIdx].name : "";
a6bddfc6
BA
231 },
232 getSid: function(pname) {
6fba6e0c
BA
233 const pIdx = this.people.findIndex(pl => pl.name == pname);
234 return (pIdx === -1 ? null : this.people[pIdx].sid);
a6bddfc6 235 },
5bd05dba 236 getPname: function(sid) {
6fba6e0c
BA
237 const pIdx = this.people.findIndex(pl => pl.sid == sid);
238 return (pIdx === -1 ? null : this.people[pIdx].name);
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
BA
251 // Challenge with targeted players
252 const targetSid = this.getSid(to);
253 if (!targetSid)
254 {
255 if (!!warnDisconnected)
256 alert("Warning: " + pname + " is not connected");
257 }
258 else
259 doSend(code, obj, targetSid);
a6bddfc6
BA
260 }
261 else
262 {
263 // Open challenge: send to all connected players (except us)
6fba6e0c 264 this.people.forEach(p => {
a6bddfc6
BA
265 if (p.sid != this.st.user.sid) //only sid is always set
266 doSend(code, obj, p.sid);
267 });
268 }
269 },
270 // Messaging center:
9d58ef95
BA
271 socketMessageListener: function(msg) {
272 const data = JSON.parse(msg.data);
273 switch (data.code)
274 {
f4f4c03c 275 // 0.2] Receive clients list (just socket IDs)
81d9ce72 276 case "pollclients":
1efe1d79 277 {
5a3da968 278 data.sockIds.forEach(sid => {
6fba6e0c 279 this.people.push({sid:sid, id:0, name:""});
81d9ce72 280 // Ask identity, challenges and game(s)
5a3da968 281 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
2ada153c 282 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
81d9ce72 283 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
5a3da968
BA
284 });
285 break;
1efe1d79 286 }
81d9ce72 287 case "askidentity":
1efe1d79 288 {
6855163c
BA
289 // Request for identification: reply if I'm not anonymous
290 if (this.st.user.id > 0)
291 {
292 this.st.conn.send(JSON.stringify(
66d03f23
BA
293 // people[0] instead of st.user to avoid sending email
294 {code:"identity", user:this.people[0], target:data.from}));
6855163c 295 }
5a3da968 296 break;
1efe1d79 297 }
dd75774d 298 case "askchallenge":
1efe1d79 299 {
6855163c 300 // Send my current live challenge (if any)
dd75774d 301 const cIdx = this.challenges
6855163c 302 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
303 if (cIdx >= 0)
304 {
305 const c = this.challenges[cIdx];
306 const myChallenge =
307 {
81d9ce72 308 // Minimal challenge informations: (from not required)
2ada153c 309 id: c.id,
81d9ce72
BA
310 to: c.to,
311 fen: c.fen,
312 vid: c.vid,
313 timeControl: c.timeControl
dd75774d
BA
314 };
315 this.st.conn.send(JSON.stringify({code:"challenge",
42c15a75 316 chall:myChallenge, target:data.from}));
81d9ce72
BA
317 }
318 break;
1efe1d79 319 }
81d9ce72 320 case "askgame":
1efe1d79 321 {
42c15a75
BA
322 // Send my current live game (if any)
323 GameStorage.getCurrent((game) => {
324 if (!!game)
325 {
326 const myGame =
327 {
328 // Minimal game informations:
329 id: game.id,
330 players: game.players.map(p => p.name),
a9b131f1 331 vid: game.vid,
42c15a75
BA
332 timeControl: game.timeControl,
333 };
334 this.st.conn.send(JSON.stringify({code:"game",
335 game:myGame, target:data.from}));
336 }
337 });
81d9ce72 338 break;
1efe1d79 339 }
5a3da968 340 case "identity":
1efe1d79 341 {
6fba6e0c
BA
342 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
343 this.people[pIdx].id = data.user.id;
344 this.people[pIdx].name = data.user.name;
5a3da968 345 break;
1efe1d79 346 }
dd75774d 347 case "challenge":
1efe1d79 348 {
dd75774d 349 // Receive challenge from some player (+sid)
6855163c 350 let newChall = data.chall;
2ada153c 351 newChall.type = this.classifyObject(data.chall);
6fba6e0c
BA
352 const pIdx = this.people.findIndex(p => p.sid == data.from);
353 newChall.from = this.people[pIdx]; //may be anonymous
42c15a75 354 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
25996aed 355 newChall.vname = this.getVname(newChall.vid);
6855163c 356 this.challenges.push(newChall);
81d9ce72 357 break;
1efe1d79 358 }
dd75774d 359 case "game":
1efe1d79 360 {
6855163c 361 // Receive game from some player (+sid)
6855163c 362 // NOTE: it may be correspondance (if newgame while we are connected)
d9b86b16
BA
363 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
364 {
365 let newGame = data.game;
366 newGame.type = this.classifyObject(data.game);
a9b131f1 367 newGame.vname = this.getVname(data.game.vid);
d9b86b16
BA
368 newGame.rid = data.from;
369 newGame.score = "*";
370 this.games.push(newGame);
371 }
81d9ce72 372 break;
1efe1d79 373 }
9d58ef95 374 case "newgame":
1efe1d79 375 {
66d03f23
BA
376 // TODO: next line required ?!
377 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
5d04793e 378 // New game just started: data contain all information
66d03f23 379 if (this.classifyObject(data.gameInfo) == "live")
5d04793e 380 this.startNewGame(data.gameInfo);
5d04793e
BA
381 else
382 {
3d55deea 383 this.infoMessage = "New game started: " +
d18bfa12
BA
384 "<a href='#/game/" + data.gameInfo.gameId + "'>" +
385 "#/game/" + data.gameInfo.gameId + "</a>";
dce792f6
BA
386 let modalBox = document.getElementById("modalInfo");
387 modalBox.checked = true;
3d55deea 388 setTimeout(() => { modalBox.checked = false; }, 3000);
5d04793e 389 }
9d58ef95 390 break;
1efe1d79 391 }
bb7dd7db
BA
392 case "refusechallenge":
393 {
485fccd5 394 alert(this.getPname(data.from) + " declined your challenge");
5bd05dba 395 ArrayFun.remove(this.challenges, c => c.id == data.cid);
bb7dd7db
BA
396 break;
397 }
1efe1d79
BA
398 case "deletechallenge":
399 {
1ba761c8 400 // NOTE: the challenge may be already removed
9d58ef95 401 ArrayFun.remove(this.challenges, c => c.id == data.cid);
66d03f23 402 localStorage.removeItem("challenge"); //in case of
9d58ef95 403 break;
1efe1d79 404 }
b4d619d1 405 case "connect":
1efe1d79 406 {
6fba6e0c 407 this.people.push({name:"", id:0, sid:data.sid});
5a3da968 408 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
f05815d7
BA
409 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
410 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
9d58ef95 411 break;
1efe1d79 412 }
b4d619d1 413 case "disconnect":
1efe1d79 414 {
6fba6e0c 415 ArrayFun.remove(this.people, p => p.sid == data.sid);
a6bddfc6 416 // Also remove all challenges sent by this player:
2ada153c
BA
417 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
418 // And all live games where he plays and no other opponent is online
419 ArrayFun.remove(this.games, g =>
420 g.type == "live" && (g.players.every(p => p.sid == data.sid
6fba6e0c 421 || !this.people.some(pl => pl.sid == p.sid))), "all");
9d58ef95 422 break;
1efe1d79 423 }
9d58ef95
BA
424 }
425 },
a6bddfc6 426 // Challenge lifecycle:
b4d619d1
BA
427 tryChallenge: function(player) {
428 if (player.id == 0)
429 return; //anonymous players cannot be challenged
a7808884 430 this.newchallenge.to = player.name;
b4d619d1 431 doClick("modalNewgame");
fb54f098 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;
9d58ef95
BA
437 const error = checkChallenge(this.newchallenge);
438 if (!!error)
439 return alert(error);
2ada153c 440 const ctype = this.classifyObject(this.newchallenge);
098cd7f1
BA
441 if (ctype == "corr" && this.st.user.id <= 0)
442 return alert("Please log in to play correspondance games");
bb7dd7db 443 // NOTE: "from" information is not required here
a7808884 444 let chall = Object.assign({}, this.newchallenge);
2ada153c 445 const finishAddChallenge = (cid,warnDisconnected) => {
1efe1d79 446 chall.id = cid || "c" + getRandString();
2ada153c 447 // Send challenge to peers (if connected)
c9695cb1 448 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
1efe1d79 449 chall.added = Date.now();
a9b131f1 450 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
bb7dd7db
BA
451 chall.type = ctype;
452 chall.vname = vname;
66d03f23 453 chall.from = this.people[0]; //avoid sending email
1efe1d79 454 this.challenges.push(chall);
f6f2bef1 455 localStorage.setItem("challenge", JSON.stringify(chall));
b4d619d1
BA
456 document.getElementById("modalNewgame").checked = false;
457 };
1efe1d79
BA
458 const cIdx = this.challenges.findIndex(
459 c => c.from.sid == this.st.user.sid && c.type == ctype);
460 if (cIdx >= 0)
b4d619d1 461 {
1efe1d79 462 // Delete current challenge (will be replaced now)
bb7dd7db 463 this.sendSomethingTo(this.challenges[cIdx].to,
1efe1d79
BA
464 "deletechallenge", {cid:this.challenges[cIdx].id});
465 if (ctype == "corr")
466 {
467 ajax(
468 "/challenges",
469 "DELETE",
470 {id: this.challenges[cIdx].id}
471 );
472 }
473 this.challenges.splice(cIdx, 1);
474 }
475 if (ctype == "live")
476 {
477 // Live challenges have a random ID
2ada153c 478 finishAddChallenge(null, "warnDisconnected");
03608482 479 }
b4d619d1 480 else
03608482 481 {
b4d619d1 482 // Correspondance game: send challenge to server
03608482 483 ajax(
1efe1d79 484 "/challenges",
03608482 485 "POST",
bebcc8d4 486 { chall: chall },
1efe1d79 487 response => { finishAddChallenge(response.cid); }
03608482 488 );
9d58ef95 489 }
fb54f098 490 },
a6bddfc6 491 clickChallenge: function(c) {
485fccd5
BA
492 const myChallenge = (c.from.sid == this.st.user.sid //live
493 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
494 if (!myChallenge)
a6bddfc6 495 {
3d55deea
BA
496 if (c.type == "corr" && this.st.user.id <= 0)
497 return alert("Please log in to accept corr challenges");
a6bddfc6 498 c.accepted = true;
485fccd5 499 if (!!c.to) //c.to == this.st.user.name (connected)
a6bddfc6
BA
500 {
501 // TODO: if special FEN, show diagram after loading variant
502 c.accepted = confirm("Accept challenge?");
503 }
485fccd5 504 if (c.accepted)
36093eba 505 {
8c564f46 506 c.seat = this.people[0]; //== this.st.user, avoid revealing email
485fccd5
BA
507 this.launchGame(c);
508 }
509 else
510 {
511 this.st.conn.send(JSON.stringify({
512 code: "refusechallenge",
513 cid: c.id, target: c.from.sid}));
36093eba 514 }
a6bddfc6 515 }
2be5d614 516 else //my challenge
485fccd5 517 {
2be5d614
BA
518 localStorage.removeItem("challenge");
519 if (c.type == "corr")
520 {
521 ajax(
522 "/challenges",
523 "DELETE",
524 {id: c.id}
525 );
526 }
485fccd5 527 }
3d55deea
BA
528 // In (almost) all cases, the challenge is consumed:
529 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
530 // NOTE: deletechallenge event might be redundant (but it's easier this way)
531 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
a6bddfc6 532 },
485fccd5 533 // NOTE: when launching game, the challenge is already deleted
36093eba 534 launchGame: async function(c) {
a9b131f1 535 const vModule = await import("@/variants/" + c.vname + ".js");
a6bddfc6 536 window.V = vModule.VariantRules;
4b0384fa
BA
537 // These game informations will be sent to other players
538 const gameInfo =
a6bddfc6 539 {
4b0384fa 540 gameId: getRandString(),
a6bddfc6 541 fen: c.fen || V.GenRandInitFen(),
5d04793e 542 players: shuffle([c.from, c.seat]), //white then black
a6bddfc6 543 vid: c.vid,
a9b131f1 544 timeControl: c.timeControl,
a6bddfc6 545 };
8c564f46
BA
546 let target = c.from.sid; //may not be defined if corr + offline opp
547 if (!target)
548 {
549 const opponent = this.people.find(p => p.id == c.from.id);
550 if (!!opponent)
551 target = opponent.sid
552 }
411d23cd
BA
553 const tryNotifyOpponent = () => {
554 if (!!target) //opponent is online
555 {
556 this.st.conn.send(JSON.stringify({code:"newgame",
557 gameInfo:gameInfo, target:target, cid:c.id}));
558 }
559 };
485fccd5 560 if (c.type == "live")
411d23cd
BA
561 {
562 tryNotifyOpponent();
485fccd5 563 this.startNewGame(gameInfo);
411d23cd 564 }
485fccd5
BA
565 else //corr: game only on server
566 {
567 ajax(
568 "/games",
569 "POST",
2be5d614 570 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
411d23cd
BA
571 response => {
572 gameInfo.gameId = response.gameId;
573 tryNotifyOpponent();
574 this.$router.push("/game/" + response.gameId);
575 }
485fccd5
BA
576 );
577 }
fb54f098 578 },
a9b131f1 579 // NOTE: for live games only (corr games start on the server)
42c15a75 580 startNewGame: function(gameInfo) {
25996aed
BA
581 const game = Object.assign({}, gameInfo, {
582 // (other) Game infos: constant
6d01bb17 583 fenStart: gameInfo.fen,
92a523d1 584 added: Date.now(),
25996aed 585 // Game state (including FEN): will be updated
967a2686 586 moves: [],
a9b131f1 587 clocks: [-1, -1], //-1 = unstarted
66d03f23 588 initime: [0, 0], //initialized later
967a2686 589 score: "*",
a7808884 590 });
967a2686 591 GameStorage.add(game);
7b626bdd
BA
592 if (this.st.settings.sound >= 1)
593 new Audio("/sounds/newgame.mp3").play().catch(err => {});
66d03f23 594 this.$router.push("/game/" + gameInfo.gameId);
1efe1d79 595 },
fb54f098 596 },
85e5b5c1 597};
ccd4a2b7 598</script>
85e5b5c1
BA
599
600<style lang="sass">
601// TODO
602</style>