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