Some fixes. TODO: check clocks update, and continue work on resign/abort/draw
[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, shuffle } from "@/utils/alea";
82 import GameList from "@/components/GameList.vue";
83 import ChallengeList from "@/components/ChallengeList.vue";
84 import { GameStorage } from "@/utils/gameStorage";
85 import { extractTime } from "@/utils/timeControl";
86 export default {
87 name: "my-hall",
88 components: {
89 GameList,
90 ChallengeList,
91 },
92 data: function () {
93 return {
94 st: store.state,
95 cdisplay: "live", //or corr
96 pdisplay: "players", //or chat
97 gdisplay: "live",
98 games: [],
99 challenges: [],
100 players: [], //online players (rename into "people" ?)
101 newchallenge: {
102 fen: "",
103 vid: 0,
104 nbPlayers: 0,
105 to: ["", "", ""], //name(s) of challenged player(s)
106 timeControl: "", //"2m+2s" ...etc
107 },
108 };
109 },
110 computed: {
111 uniquePlayers: function() {
112 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
113 let anonymous = {id:0, name:"@nonymous", count:0};
114 let playerList = [];
115 this.players.forEach(p => {
116 if (p.id > 0)
117 playerList.push(p);
118 else
119 anonymous.count++;
120 });
121 if (anonymous.count > 0)
122 playerList.push(anonymous);
123 return playerList;
124 },
125 },
126 created: function() {
127 // Always add myself to players' list
128 this.players.push(this.st.user);
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 }
152 // 0.1] Ask server for room composition:
153 const socketOpenListener = () => {
154 this.st.conn.send(JSON.stringify({code:"pollclients"}));
155 };
156 this.st.conn.onopen = socketOpenListener;
157 // TODO: is this required here?
158 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
159 this.st.conn.onmessage = this.socketMessageListener;
160 const oldOnclose = this.st.conn.onclose;
161 const socketCloseListener = () => {
162 oldOnclose(); //reinitialize connexion (in store.js)
163 this.st.conn.addEventListener('message', this.socketMessageListener);
164 this.st.conn.addEventListener('close', socketCloseListener);
165 };
166 this.st.conn.onclose = socketCloseListener;
167 },
168 methods: {
169 // Helpers:
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 },
176 classifyObject: function(o) { //challenge or game
177 // Heuristic: should work for most cases... (TODO)
178 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
179 },
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 },
187 showGame: function(g) {
188 // NOTE: we are an observer, since only games I don't play are shown here
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);
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 },
206 getPname: function(sid) {
207 const pIdx = this.players.findIndex(pl => pl.sid == sid);
208 return (pIdx === -1 ? null : this.players[pIdx].name);
209 },
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 };
219 if (!!to[0])
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:
243 socketMessageListener: function(msg) {
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)
246 this.oldOnmessage(msg);
247 const data = JSON.parse(msg.data);
248 switch (data.code)
249 {
250 // 0.2] Receive clients list (just socket IDs)
251 case "pollclients":
252 {
253 data.sockIds.forEach(sid => {
254 this.players.push({sid:sid, id:0, name:""});
255 // Ask identity, challenges and game(s)
256 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
257 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
258 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
259 });
260 break;
261 }
262 case "askidentity":
263 {
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 }
270 break;
271 }
272 case "askchallenge":
273 {
274 // Send my current live challenge (if any)
275 const cIdx = this.challenges
276 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
277 if (cIdx >= 0)
278 {
279 const c = this.challenges[cIdx];
280 const myChallenge =
281 {
282 // Minimal challenge informations: (from not required)
283 id: c.id,
284 to: c.to,
285 fen: c.fen,
286 vid: c.vid,
287 timeControl: c.timeControl
288 };
289 this.st.conn.send(JSON.stringify({code:"challenge",
290 challenge:myChallenge, target:data.from}));
291 }
292 break;
293 }
294 case "askgame":
295 {
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 // }
311 break;
312 }
313 case "identity":
314 {
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;
318 break;
319 }
320 case "challenge":
321 {
322 // Receive challenge from some player (+sid)
323 let newChall = data.chall;
324 newChall.type = this.classifyObject(data.chall);
325 const pIdx = this.players.findIndex(p => p.sid == data.from);
326 newChall.from = this.players[pIdx]; //may be anonymous
327 newChall.added = Date.now();
328 newChall.vname = this.getVname(newChall.vid);
329 this.challenges.push(newChall);
330 break;
331 }
332 case "game":
333 {
334 // Receive game from some player (+sid)
335 // NOTE: it may be correspondance (if newgame while we are connected)
336 // TODO: ambiguous naming "newGame" ==> rename function ?
337 let newGame = data.game;
338 newGame.type = this.classifyObject(data.game);
339 newGame.vname = newGame.vname;
340 this.games.push(newGame);
341 break;
342 }
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
345 case "newgame":
346 {
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);
351 break;
352 }
353 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
354 // NOTE: challenge "socket" actions accept+withdraw only for live challenges
355 case "acceptchallenge":
356 {
357 // Someone accept an open (or targeted) challenge
358 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
359 let c = this.challenges[cIdx];
360 if (!c.seats)
361 c.seats = [...Array(c.to.length)];
362 const pIdx = this.players.findIndex(p => p.sid == data.from);
363 // Put this player in the first empty seat we find:
364 let sIdx = 0;
365 for (; sIdx<c.seats.length; sIdx++)
366 {
367 if (!c.seats[sIdx])
368 {
369 c.seats[sIdx] = this.players[pIdx];
370 break;
371 }
372 }
373 if (sIdx == c.seats.length - 1)
374 {
375 // All seats are taken: game can start
376 this.launchGame(c);
377 }
378 break;
379 }
380 case "withdrawchallenge":
381 {
382 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
383 let seats = this.challenges[cIdx].seats;
384 const sIdx = seats.findIndex(s => s.sid == data.sid);
385 seats[sIdx] = undefined;
386 break;
387 }
388 case "refusechallenge":
389 {
390 alert(this.getPname(data.from) + " refused your challenge");
391 ArrayFun.remove(this.challenges, c => c.id == data.cid);
392 break;
393 }
394 case "deletechallenge":
395 {
396 ArrayFun.remove(this.challenges, c => c.id == data.cid);
397 break;
398 }
399 case "connect":
400 {
401 this.players.push({name:"", id:0, sid:data.sid});
402 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
403 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
404 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
405 break;
406 }
407 case "disconnect":
408 {
409 ArrayFun.remove(this.players, p => p.sid == data.sid);
410 // Also remove all challenges sent by this player:
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");
416 break;
417 }
418 }
419 },
420 // Challenge lifecycle:
421 tryChallenge: function(player) {
422 if (player.id == 0)
423 return; //anonymous players cannot be challenged
424 this.newchallenge.to[0] = player.name;
425 doClick("modalNewgame");
426 },
427 newChallenge: async function() {
428 const vname = this.getVname(this.newchallenge.vid);
429 const vModule = await import("@/variants/" + vname + ".js");
430 window.V = vModule.VariantRules;
431 const error = checkChallenge(this.newchallenge);
432 if (!!error)
433 return alert(error);
434 const ctype = this.classifyObject(this.newchallenge);
435 const cto = this.newchallenge.to.slice(0, this.newchallenge.nbPlayers - 1);
436 // NOTE: "from" information is not required here
437 let chall =
438 {
439 fen: this.newchallenge.fen,
440 to: cto,
441 timeControl: this.newchallenge.timeControl,
442 vid: this.newchallenge.vid,
443 };
444 const finishAddChallenge = (cid,warnDisconnected) => {
445 chall.id = cid || "c" + getRandString();
446 // Send challenge to peers (if connected)
447 this.sendSomethingTo(cto, "challenge", {chall:chall}, !!warnDisconnected);
448 chall.added = Date.now();
449 chall.type = ctype;
450 chall.vname = vname;
451 chall.from = this.st.user;
452 this.challenges.push(chall);
453 document.getElementById("modalNewgame").checked = false;
454 };
455 const cIdx = this.challenges.findIndex(
456 c => c.from.sid == this.st.user.sid && c.type == ctype);
457 if (cIdx >= 0)
458 {
459 // Delete current challenge (will be replaced now)
460 this.sendSomethingTo(this.challenges[cIdx].to,
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
475 finishAddChallenge(null, "warnDisconnected");
476 }
477 else
478 {
479 // Correspondance game: send challenge to server
480 ajax(
481 "/challenges",
482 "POST",
483 chall,
484 response => { finishAddChallenge(response.cid); }
485 );
486 }
487 },
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) {
496
497 console.log("click challenge");
498 console.log(c);
499
500 if (!!c.accepted)
501 {
502 this.st.conn.send(JSON.stringify({code: "withdrawchallenge",
503 cid: c.id, target: c.from.sid}));
504 if (c.type == "corr")
505 {
506 ajax(
507 "/challenges",
508 "PUT",
509 {action:"withdraw", id: this.challenges[cIdx].id}
510 );
511 }
512 c.accepted = false;
513 }
514 else if (c.from.sid == this.st.user.sid
515 || (this.st.user.id > 0 && c.from.id == this.st.user.id))
516 {
517 // It's my challenge: cancel it
518 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
519 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
520 if (c.type == "corr")
521 {
522 ajax(
523 "/challenges",
524 "DELETE",
525 {id: this.challenges[cIdx].id}
526 );
527 }
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({
538 code: (c.accepted ? "accept" : "refuse") + "challenge",
539 cid: c.id, target: c.from.sid}));
540 if (c.type == "corr" && c.accepted)
541 {
542 ajax(
543 "/challenges",
544 "PUT",
545 {action: "accept", id: this.challenges[cIdx].id}
546 );
547 }
548 if (!c.accepted)
549 {
550 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
551 if (c.type == "corr")
552 {
553 ajax(
554 "/challenges",
555 "DELETE",
556 {id: this.challenges[cIdx].id}
557 );
558 }
559 }
560 }
561 },
562 // NOTE: for live games only (corr games are launched on server)
563 launchGame: async function(c) {
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);
570 // These game informations will be sent to other players
571 const gameInfo =
572 {
573 gameId: getRandString(),
574 fen: c.fen || V.GenRandInitFen(),
575 // Players' names may be required if game start when a player is offline
576 // Shuffle players order (white then black then other colors).
577 players: shuffle(players.map(p => { return {name:p.name, sid:p.sid} })),
578 vid: c.vid,
579 timeControl: c.timeControl,
580 };
581 c.seats.forEach(s => {
582 // NOTE: cid required to remove challenge
583 this.st.conn.send(JSON.stringify({code:"newgame",
584 gameInfo:gameInfo, cid:c.id, target:s.sid}));
585 });
586 // Delete corresponding challenge:
587 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
588 this.newGame(gameInfo); //also!
589 },
590 // NOTE: for live games only (corr games are launched on server)
591 newGame: function(gameInfo) {
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
598 gameId: gameInfo.gameId,
599 vname: this.getVname(gameInfo.vid),
600 fenStart: gameInfo.fen,
601 players: gameInfo.players,
602 timeControl: gameInfo.timeControl,
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);
613 if (this.st.settings.sound >= 1)
614 new Audio("/sounds/newgame.mp3").play().catch(err => {});
615 // TODO: redirect to game
616 },
617 },
618 };
619 </script>
620
621 <style lang="sass">
622 // TODO
623 </style>
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 -->