Some fixes. TODO: check clocks update, and continue work on resign/abort/draw
[vchess.git] / client / src / views / Hall.vue
CommitLineData
ccd4a2b7 1<template lang="pug">
9d58ef95 2main
5b020e73
BA
3 input#modalNewgame.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="titleFenedit")
5 .card.smallpad
6 label#closeNewgame.modal-close(for="modalNewgame")
7 fieldset
8 label(for="selectVariant") {{ st.tr["Variant"] }}
9d58ef95 9 select#selectVariant(v-model="newchallenge.vid")
85e5b5c1 10 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
5b020e73
BA
11 fieldset
12 label(for="selectNbPlayers") {{ st.tr["Number of players"] }}
9d58ef95 13 select#selectNbPlayers(v-model="newchallenge.nbPlayers")
81d9ce72 14 option(v-show="possibleNbplayers(2)" value="2" selected) 2
5b020e73
BA
15 option(v-show="possibleNbplayers(3)" value="3") 3
16 option(v-show="possibleNbplayers(4)" value="4") 4
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)"] }}
5b020e73 23 #selectPlayers
81d9ce72 24 input(type="text" v-model="newchallenge.to[0]")
9d58ef95 25 input(v-show="newchallenge.nbPlayers>=3" type="text"
81d9ce72 26 v-model="newchallenge.to[1]")
9d58ef95 27 input(v-show="newchallenge.nbPlayers==4" type="text"
81d9ce72 28 v-model="newchallenge.to[2]")
b4d619d1 29 fieldset(v-if="st.user.id > 0")
9d58ef95
BA
30 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
31 input#inputFen(type="text" v-model="newchallenge.fen")
b4d619d1 32 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
9d58ef95
BA
33 .row
34 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
35 button(onClick="doClick('modalNewgame')") New game
36 .row
1efe1d79 37 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
6855163c
BA
38 .collapse
39 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
40 label(for="challengeSection" aria-hidden="true") Challenges
41 div
42 .button-group
43 button(@click="cdisplay='live'") Live Challenges
44 button(@click="cdisplay='corr'") Correspondance challenges
45 ChallengeList(v-show="cdisplay=='live'"
46 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
47 ChallengeList(v-show="cdisplay=='corr'"
48 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
1efe1d79 49 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
6855163c
BA
50 label(for="peopleSection" aria-hidden="true") People
51 div
1efe1d79
BA
52 .button-group
53 button(@click="pdisplay='players'") Players
54 button(@click="pdisplay='chat'") Chat
6855163c
BA
55 #players(v-show="pdisplay=='players'")
56 h3 Online players
57 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
58 :class="{anonymous: !!p.count}"
59 )
60 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
61 #chat(v-show="pdisplay=='chat'")
62 h3 Chat (TODO)
1efe1d79 63 input#gameSection(type="radio" aria-hidden="true" name="accordion")
6855163c
BA
64 label(for="gameSection" aria-hidden="true") Games
65 div
66 .button-group
67 button(@click="gdisplay='live'") Live games
68 button(@click="gdisplay='corr'") Correspondance games
69 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
70 @show-game="showGame")
71 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
72 @show-game="showGame")
625022fd
BA
73</template>
74
75<script>
5b020e73 76import { store } from "@/store";
85e5b5c1 77import { NbPlayers } from "@/data/nbPlayers";
9d58ef95
BA
78import { checkChallenge } from "@/data/challengeCheck";
79import { ArrayFun } from "@/utils/array";
03608482 80import { ajax } from "@/utils/ajax";
4b0384fa 81import { getRandString, shuffle } from "@/utils/alea";
5b020e73
BA
82import GameList from "@/components/GameList.vue";
83import ChallengeList from "@/components/ChallengeList.vue";
967a2686
BA
84import { GameStorage } from "@/utils/gameStorage";
85import { extractTime } from "@/utils/timeControl";
625022fd 86export default {
cf2343ce 87 name: "my-hall",
5b020e73
BA
88 components: {
89 GameList,
90 ChallengeList,
91 },
fb54f098
BA
92 data: function () {
93 return {
5b020e73 94 st: store.state,
6855163c
BA
95 cdisplay: "live", //or corr
96 pdisplay: "players", //or chat
fb54f098 97 gdisplay: "live",
6855163c 98 games: [],
b4d619d1 99 challenges: [],
1efe1d79 100 players: [], //online players (rename into "people" ?)
9d58ef95 101 newchallenge: {
fb54f098
BA
102 fen: "",
103 vid: 0,
104 nbPlayers: 0,
98f48579 105 to: ["", "", ""], //name(s) of challenged player(s)
6faa92f2 106 timeControl: "", //"2m+2s" ...etc
fb54f098
BA
107 },
108 };
109 },
b4d619d1
BA
110 computed: {
111 uniquePlayers: function() {
6855163c 112 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
4d64881e
BA
113 let anonymous = {id:0, name:"@nonymous", count:0};
114 let playerList = [];
b4d619d1
BA
115 this.players.forEach(p => {
116 if (p.id > 0)
117 playerList.push(p);
118 else
4d64881e 119 anonymous.count++;
b4d619d1 120 });
4d64881e
BA
121 if (anonymous.count > 0)
122 playerList.push(anonymous);
b4d619d1
BA
123 return playerList;
124 },
125 },
9d58ef95 126 created: function() {
4d64881e
BA
127 // Always add myself to players' list
128 this.players.push(this.st.user);
98f48579
BA
129 if (this.st.user.id > 0)
130 {
131 // Ask server for current corr games (all but mines)
132// ajax(
133// "/games",
134// "GET",
135// {excluded: this.st.user.id},
136// response => {
137// this.games = this.games.concat(response.games);
138// }
139// );
140 // Also ask for corr challenges (open + sent to me)
141 ajax(
142 "/challenges",
143 "GET",
144 {uid: this.st.user.id},
145 response => {
146 console.log(response.challenges);
147 // TODO: post-treatment on challenges ?
148 this.challenges = this.challenges.concat(response.challenges);
149 }
150 );
151 }
2ada153c 152 // 0.1] Ask server for room composition:
4d64881e 153 const socketOpenListener = () => {
81d9ce72 154 this.st.conn.send(JSON.stringify({code:"pollclients"}));
4d64881e
BA
155 };
156 this.st.conn.onopen = socketOpenListener;
81d9ce72
BA
157 // TODO: is this required here?
158 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
4d64881e 159 this.st.conn.onmessage = this.socketMessageListener;
052d17ea 160 const oldOnclose = this.st.conn.onclose;
4d64881e 161 const socketCloseListener = () => {
052d17ea 162 oldOnclose(); //reinitialize connexion (in store.js)
4d64881e
BA
163 this.st.conn.addEventListener('message', this.socketMessageListener);
164 this.st.conn.addEventListener('close', socketCloseListener);
165 };
166 this.st.conn.onclose = socketCloseListener;
9d58ef95 167 },
fb54f098 168 methods: {
a6bddfc6 169 // Helpers:
6855163c
BA
170 filterChallenges: function(type) {
171 return this.challenges.filter(c => c.type == type);
172 },
173 filterGames: function(type) {
174 return this.games.filter(c => c.type == type);
175 },
2ada153c 176 classifyObject: function(o) { //challenge or game
6855163c 177 // Heuristic: should work for most cases... (TODO)
2ada153c 178 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
6855163c 179 },
a6bddfc6
BA
180 possibleNbplayers: function(nbp) {
181 if (this.newchallenge.vid == 0)
182 return false;
183 const idxInVariants =
184 this.st.variants.findIndex(v => v.id == this.newchallenge.vid);
185 return NbPlayers[this.st.variants[idxInVariants].name].includes(nbp);
186 },
2ada153c 187 showGame: function(g) {
5bd05dba 188 // NOTE: we are an observer, since only games I don't play are shown here
2ada153c
BA
189 // ==> Moves sent by connected remote player(s) if live game
190 let url = "/" + g.id;
191 if (g.type == "live")
192 {
193 const sids = g.players.map(p => p.sid).join(",");
194 url += "?sids=" + sids;
195 }
196 this.$router.push(url);
a6bddfc6
BA
197 },
198 getVname: function(vid) {
199 const vIdx = this.st.variants.findIndex(v => v.id == vid);
200 return this.st.variants[vIdx].name;
201 },
202 getSid: function(pname) {
203 const pIdx = this.players.findIndex(pl => pl.name == pname);
204 return (pIdx === -1 ? null : this.players[pIdx].sid);
205 },
5bd05dba
BA
206 getPname: function(sid) {
207 const pIdx = this.players.findIndex(pl => pl.sid == sid);
208 return (pIdx === -1 ? null : this.players[pIdx].name);
209 },
a6bddfc6
BA
210 sendSomethingTo: function(to, code, obj, warnDisconnected) {
211 const doSend = (code, obj, sid) => {
212 this.st.conn.send(JSON.stringify(Object.assign(
213 {},
214 {code: code},
215 obj,
216 {target: sid}
217 )));
218 };
36093eba 219 if (!!to[0])
a6bddfc6
BA
220 {
221 to.forEach(pname => {
222 // Challenge with targeted players
223 const targetSid = this.getSid(pname);
224 if (!targetSid)
225 {
226 if (!!warnDisconnected)
227 alert("Warning: " + pname + " is not connected");
228 }
229 else
230 doSend(code, obj, targetSid);
231 });
232 }
233 else
234 {
235 // Open challenge: send to all connected players (except us)
236 this.players.forEach(p => {
237 if (p.sid != this.st.user.sid) //only sid is always set
238 doSend(code, obj, p.sid);
239 });
240 }
241 },
242 // Messaging center:
9d58ef95 243 socketMessageListener: function(msg) {
052d17ea
BA
244 // Save and call current st.conn.onmessage if one was already defined
245 // --> also needed in future Game.vue (also in Chat.vue component)
052d17ea 246 this.oldOnmessage(msg);
9d58ef95
BA
247 const data = JSON.parse(msg.data);
248 switch (data.code)
249 {
f4f4c03c 250 // 0.2] Receive clients list (just socket IDs)
81d9ce72 251 case "pollclients":
1efe1d79 252 {
5a3da968
BA
253 data.sockIds.forEach(sid => {
254 this.players.push({sid:sid, id:0, name:""});
81d9ce72 255 // Ask identity, challenges and game(s)
5a3da968 256 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
2ada153c 257 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
81d9ce72 258 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
5a3da968
BA
259 });
260 break;
1efe1d79 261 }
81d9ce72 262 case "askidentity":
1efe1d79 263 {
6855163c
BA
264 // Request for identification: reply if I'm not anonymous
265 if (this.st.user.id > 0)
266 {
267 this.st.conn.send(JSON.stringify(
268 {code:"identity", user:this.st.user, target:data.from}));
269 }
5a3da968 270 break;
1efe1d79 271 }
dd75774d 272 case "askchallenge":
1efe1d79 273 {
6855163c 274 // Send my current live challenge (if any)
dd75774d 275 const cIdx = this.challenges
6855163c 276 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
dd75774d
BA
277 if (cIdx >= 0)
278 {
279 const c = this.challenges[cIdx];
280 const myChallenge =
281 {
81d9ce72 282 // Minimal challenge informations: (from not required)
2ada153c 283 id: c.id,
81d9ce72
BA
284 to: c.to,
285 fen: c.fen,
286 vid: c.vid,
287 timeControl: c.timeControl
dd75774d
BA
288 };
289 this.st.conn.send(JSON.stringify({code:"challenge",
1efe1d79 290 challenge:myChallenge, target:data.from}));
81d9ce72
BA
291 }
292 break;
1efe1d79 293 }
81d9ce72 294 case "askgame":
1efe1d79 295 {
967a2686
BA
296 // Send my current live games (if any)
297 // TODO: from indexedDB, through GameStorage.
298// if (!!localStorage["gid"])
299// {
300// const myGame =
301// {
302// // Minimal game informations: (fen+clock not required)
303// id: localStorage["gid"],
304// players: JSON.parse(localStorage["players"]), //array sid+id+name
305// vname: localStorage["vname"],
306// timeControl: localStorage["timeControl"],
307// };
308// this.st.conn.send(JSON.stringify({code:"game",
309// game:myGame, target:data.from}));
310// }
81d9ce72 311 break;
1efe1d79 312 }
5a3da968 313 case "identity":
1efe1d79 314 {
6855163c
BA
315 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
316 this.players[pIdx].id = data.user.id;
317 this.players[pIdx].name = data.user.name;
5a3da968 318 break;
1efe1d79 319 }
dd75774d 320 case "challenge":
1efe1d79 321 {
dd75774d 322 // Receive challenge from some player (+sid)
6855163c 323 let newChall = data.chall;
2ada153c 324 newChall.type = this.classifyObject(data.chall);
bb7dd7db 325 const pIdx = this.players.findIndex(p => p.sid == data.from);
6855163c 326 newChall.from = this.players[pIdx]; //may be anonymous
1efe1d79 327 newChall.added = Date.now();
bb7dd7db 328 newChall.vname = this.getVname(newChall.vid);
6855163c 329 this.challenges.push(newChall);
81d9ce72 330 break;
1efe1d79 331 }
dd75774d 332 case "game":
1efe1d79 333 {
6855163c 334 // Receive game from some player (+sid)
6855163c 335 // NOTE: it may be correspondance (if newgame while we are connected)
967a2686 336 // TODO: ambiguous naming "newGame" ==> rename function ?
2ada153c
BA
337 let newGame = data.game;
338 newGame.type = this.classifyObject(data.game);
7b626bdd 339 newGame.vname = newGame.vname;
2ada153c 340 this.games.push(newGame);
81d9ce72 341 break;
1efe1d79 342 }
b4d619d1
BA
343// * - receive "new game": if live, store locally + redirect to game
344// * If corr: notify "new game has started", give link, but do not redirect
9d58ef95 345 case "newgame":
1efe1d79 346 {
5bd05dba
BA
347 // Delete corresponding challenge:
348 ArrayFun.remove(this.challenges, c => c.id == data.cid);
349 // New game just started: data contain all informations
350 this.newGame(data.gameInfo);
b4d619d1 351 break;
1efe1d79 352 }
b4d619d1 353// * - receive "accept/withdraw/cancel challenge": apply action to challenges list
a6bddfc6 354 // NOTE: challenge "socket" actions accept+withdraw only for live challenges
9d58ef95 355 case "acceptchallenge":
1efe1d79 356 {
bb7dd7db 357 // Someone accept an open (or targeted) challenge
1efe1d79 358 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
a6bddfc6
BA
359 let c = this.challenges[cIdx];
360 if (!c.seats)
361 c.seats = [...Array(c.to.length)];
bb7dd7db 362 const pIdx = this.players.findIndex(p => p.sid == data.from);
a6bddfc6
BA
363 // Put this player in the first empty seat we find:
364 let sIdx = 0;
365 for (; sIdx<c.seats.length; sIdx++)
1efe1d79 366 {
a6bddfc6 367 if (!c.seats[sIdx])
1efe1d79 368 {
a6bddfc6 369 c.seats[sIdx] = this.players[pIdx];
1efe1d79
BA
370 break;
371 }
372 }
a6bddfc6
BA
373 if (sIdx == c.seats.length - 1)
374 {
375 // All seats are taken: game can start
376 this.launchGame(c);
377 }
9d58ef95 378 break;
1efe1d79 379 }
9d58ef95 380 case "withdrawchallenge":
1efe1d79 381 {
9d58ef95 382 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
a6bddfc6
BA
383 let seats = this.challenges[cIdx].seats;
384 const sIdx = seats.findIndex(s => s.sid == data.sid);
385 seats[sIdx] = undefined;
9d58ef95 386 break;
1efe1d79 387 }
bb7dd7db
BA
388 case "refusechallenge":
389 {
5bd05dba
BA
390 alert(this.getPname(data.from) + " refused your challenge");
391 ArrayFun.remove(this.challenges, c => c.id == data.cid);
bb7dd7db
BA
392 break;
393 }
1efe1d79
BA
394 case "deletechallenge":
395 {
9d58ef95
BA
396 ArrayFun.remove(this.challenges, c => c.id == data.cid);
397 break;
1efe1d79 398 }
b4d619d1 399 case "connect":
1efe1d79 400 {
5a3da968
BA
401 this.players.push({name:"", id:0, sid:data.sid});
402 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
f05815d7
BA
403 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
404 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
9d58ef95 405 break;
1efe1d79 406 }
b4d619d1 407 case "disconnect":
1efe1d79 408 {
5a3da968 409 ArrayFun.remove(this.players, p => p.sid == data.sid);
a6bddfc6 410 // Also remove all challenges sent by this player:
2ada153c
BA
411 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
412 // And all live games where he plays and no other opponent is online
413 ArrayFun.remove(this.games, g =>
414 g.type == "live" && (g.players.every(p => p.sid == data.sid
415 || !this.players.some(pl => pl.sid == p.sid))), "all");
9d58ef95 416 break;
1efe1d79 417 }
9d58ef95
BA
418 }
419 },
a6bddfc6 420 // Challenge lifecycle:
b4d619d1
BA
421 tryChallenge: function(player) {
422 if (player.id == 0)
423 return; //anonymous players cannot be challenged
81d9ce72 424 this.newchallenge.to[0] = player.name;
b4d619d1 425 doClick("modalNewgame");
fb54f098 426 },
9d58ef95 427 newChallenge: async function() {
bb7dd7db 428 const vname = this.getVname(this.newchallenge.vid);
1efe1d79
BA
429 const vModule = await import("@/variants/" + vname + ".js");
430 window.V = vModule.VariantRules;
9d58ef95
BA
431 const error = checkChallenge(this.newchallenge);
432 if (!!error)
433 return alert(error);
2ada153c 434 const ctype = this.classifyObject(this.newchallenge);
98f48579 435 const cto = this.newchallenge.to.slice(0, this.newchallenge.nbPlayers - 1);
bb7dd7db 436 // NOTE: "from" information is not required here
1efe1d79 437 let chall =
dd75774d 438 {
a6bddfc6 439 fen: this.newchallenge.fen,
1efe1d79 440 to: cto,
5578a7bf 441 timeControl: this.newchallenge.timeControl,
1efe1d79 442 vid: this.newchallenge.vid,
5578a7bf 443 };
2ada153c 444 const finishAddChallenge = (cid,warnDisconnected) => {
1efe1d79 445 chall.id = cid || "c" + getRandString();
2ada153c
BA
446 // Send challenge to peers (if connected)
447 this.sendSomethingTo(cto, "challenge", {chall:chall}, !!warnDisconnected);
1efe1d79 448 chall.added = Date.now();
bb7dd7db
BA
449 chall.type = ctype;
450 chall.vname = vname;
451 chall.from = this.st.user;
1efe1d79 452 this.challenges.push(chall);
b4d619d1
BA
453 document.getElementById("modalNewgame").checked = false;
454 };
1efe1d79
BA
455 const cIdx = this.challenges.findIndex(
456 c => c.from.sid == this.st.user.sid && c.type == ctype);
457 if (cIdx >= 0)
b4d619d1 458 {
1efe1d79 459 // Delete current challenge (will be replaced now)
bb7dd7db 460 this.sendSomethingTo(this.challenges[cIdx].to,
1efe1d79
BA
461 "deletechallenge", {cid:this.challenges[cIdx].id});
462 if (ctype == "corr")
463 {
464 ajax(
465 "/challenges",
466 "DELETE",
467 {id: this.challenges[cIdx].id}
468 );
469 }
470 this.challenges.splice(cIdx, 1);
471 }
472 if (ctype == "live")
473 {
474 // Live challenges have a random ID
2ada153c 475 finishAddChallenge(null, "warnDisconnected");
03608482 476 }
b4d619d1 477 else
03608482 478 {
b4d619d1 479 // Correspondance game: send challenge to server
03608482 480 ajax(
1efe1d79 481 "/challenges",
03608482 482 "POST",
052d17ea 483 chall,
1efe1d79 484 response => { finishAddChallenge(response.cid); }
03608482 485 );
9d58ef95 486 }
fb54f098 487 },
a6bddfc6
BA
488// * - accept challenge (corr or live) --> send info to challenge creator
489// * - cancel challenge (click on sent challenge) --> send info to all concerned players
490// * - withdraw from challenge (if >= 3 players and previously accepted)
491// * --> send info to challenge creator
492// * - refuse challenge: send "refuse" to challenge sender, and "delete" to others
493// * - prepare and start new game (if challenge is full after acceptation)
494// * --> include challenge ID (so that opponents can delete the challenge too)
495 clickChallenge: function(c) {
98f48579
BA
496
497 console.log("click challenge");
d7371164 498 console.log(c);
98f48579 499
36093eba 500 if (!!c.accepted)
2ada153c 501 {
36093eba
BA
502 this.st.conn.send(JSON.stringify({code: "withdrawchallenge",
503 cid: c.id, target: c.from.sid}));
504 if (c.type == "corr")
505 {
2ada153c
BA
506 ajax(
507 "/challenges",
508 "PUT",
509 {action:"withdraw", id: this.challenges[cIdx].id}
510 );
36093eba
BA
511 }
512 c.accepted = false;
a6bddfc6 513 }
36093eba
BA
514 else if (c.from.sid == this.st.user.sid
515 || (this.st.user.id > 0 && c.from.id == this.st.user.id))
a6bddfc6 516 {
36093eba 517 // It's my challenge: cancel it
a6bddfc6
BA
518 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
519 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
36093eba
BA
520 if (c.type == "corr")
521 {
522 ajax(
523 "/challenges",
524 "DELETE",
525 {id: this.challenges[cIdx].id}
526 );
527 }
a6bddfc6
BA
528 }
529 else //accept (or refuse) a challenge
530 {
531 c.accepted = true;
532 if (!!c.to[0])
533 {
534 // TODO: if special FEN, show diagram after loading variant
535 c.accepted = confirm("Accept challenge?");
536 }
537 this.st.conn.send(JSON.stringify({
4edfed6c 538 code: (c.accepted ? "accept" : "refuse") + "challenge",
a6bddfc6 539 cid: c.id, target: c.from.sid}));
4edfed6c 540 if (c.type == "corr" && c.accepted)
36093eba
BA
541 {
542 ajax(
543 "/challenges",
544 "PUT",
4edfed6c 545 {action: "accept", id: this.challenges[cIdx].id}
36093eba
BA
546 );
547 }
a6bddfc6 548 if (!c.accepted)
36093eba 549 {
a6bddfc6 550 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
36093eba
BA
551 if (c.type == "corr")
552 {
553 ajax(
554 "/challenges",
555 "DELETE",
556 {id: this.challenges[cIdx].id}
557 );
558 }
559 }
a6bddfc6
BA
560 }
561 },
f05815d7 562 // NOTE: for live games only (corr games are launched on server)
36093eba 563 launchGame: async function(c) {
a6bddfc6
BA
564 // Just assign colors and pass the message
565 const vname = this.getVname(c.vid);
566 const vModule = await import("@/variants/" + vname + ".js");
567 window.V = vModule.VariantRules;
568 let players = [c.from];
569 Array.prototype.push.apply(players, c.seats);
4b0384fa
BA
570 // These game informations will be sent to other players
571 const gameInfo =
a6bddfc6 572 {
4b0384fa 573 gameId: getRandString(),
a6bddfc6 574 fen: c.fen || V.GenRandInitFen(),
5bd05dba 575 // Players' names may be required if game start when a player is offline
4b0384fa
BA
576 // Shuffle players order (white then black then other colors).
577 players: shuffle(players.map(p => { return {name:p.name, sid:p.sid} })),
a6bddfc6
BA
578 vid: c.vid,
579 timeControl: c.timeControl,
580 };
581 c.seats.forEach(s => {
5bd05dba 582 // NOTE: cid required to remove challenge
a6bddfc6 583 this.st.conn.send(JSON.stringify({code:"newgame",
5bd05dba 584 gameInfo:gameInfo, cid:c.id, target:s.sid}));
a6bddfc6 585 });
5bd05dba
BA
586 // Delete corresponding challenge:
587 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
a6bddfc6 588 this.newGame(gameInfo); //also!
fb54f098 589 },
7b626bdd 590 // NOTE: for live games only (corr games are launched on server)
a6bddfc6 591 newGame: function(gameInfo) {
967a2686
BA
592 // Extract times (in [milli]seconds), set clocks
593 const tc = extractTime(gameInfo.timeControl);
594 const IPlayFirst = (gameInfo.players[0].sid == this.st.user.sid);
595 const game =
596 {
597 // Game infos: constant
4b0384fa 598 gameId: gameInfo.gameId,
6d01bb17
BA
599 vname: this.getVname(gameInfo.vid),
600 fenStart: gameInfo.fen,
601 players: gameInfo.players,
602 timeControl: gameInfo.timeControl,
967a2686
BA
603 increment: tc.increment,
604 mode: "live", //function for live games only
605 // Game state: will be updated
606 fen: gameInfo.fen,
607 moves: [],
608 clocks: [...Array(gameInfo.players.length)].fill(tc.mainTime),
609 initime: (IPlayFirst ? Date.now() : undefined),
610 score: "*",
611 };
612 GameStorage.add(game);
7b626bdd
BA
613 if (this.st.settings.sound >= 1)
614 new Audio("/sounds/newgame.mp3").play().catch(err => {});
a6088c90 615 // TODO: redirect to game
1efe1d79 616 },
fb54f098 617 },
85e5b5c1 618};
ccd4a2b7 619</script>
85e5b5c1
BA
620
621<style lang="sass">
622// TODO
623</style>
967a2686
BA
624
625<!--
626// TODO:
627// Remove duplicates if several players of one game send their game info (Hall)
628// When click on it, assign a random rid among online players (max. 4).
629-->