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