Saving state
[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 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 of challenged players
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 // Ask server for current corr games (all but mines)
128 // ajax(
129 // "",
130 // "GET",
131 // response => {
132 //
133 // }
134 // );
135 // // Also ask for corr challenges (all)
136 // ajax(
137 // "",
138 // "GET",
139 // response => {
140 //
141 // }
142 // );
143 // 0.1] Ask server for for room composition:
144 const socketOpenListener = () => {
145 this.st.conn.send(JSON.stringify({code:"pollclients"}));
146 };
147 this.st.conn.onopen = socketOpenListener;
148 // TODO: is this required here?
149 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
150 this.st.conn.onmessage = this.socketMessageListener;
151 const oldOnclose = this.st.conn.onclose;
152 const socketCloseListener = () => {
153 oldOnclose(); //reinitialize connexion (in store.js)
154 this.st.conn.addEventListener('message', this.socketMessageListener);
155 this.st.conn.addEventListener('close', socketCloseListener);
156 };
157 this.st.conn.onclose = socketCloseListener;
158 },
159 methods: {
160 // Helpers:
161 filterChallenges: function(type) {
162 return this.challenges.filter(c => c.type == type);
163 },
164 filterGames: function(type) {
165 return this.games.filter(c => c.type == type);
166 },
167 classifyChallenge: function(c) {
168 // Heuristic: should work for most cases... (TODO)
169 return (c.timeControl.indexOf('d') === -1 ? "live" : "corr");
170 },
171 possibleNbplayers: function(nbp) {
172 if (this.newchallenge.vid == 0)
173 return false;
174 const idxInVariants =
175 this.st.variants.findIndex(v => v.id == this.newchallenge.vid);
176 return NbPlayers[this.st.variants[idxInVariants].name].includes(nbp);
177 },
178 showGame: function(game) {
179 // NOTE: if we are an observer, the game will be found in main games list
180 // (sent by connected remote players)
181 // TODO: game path ? /vname/gameId seems better
182 this.$router.push("/" + game.id);
183 },
184 getVname: function(vid) {
185 const vIdx = this.st.variants.findIndex(v => v.id == vid);
186 return this.st.variants[vIdx].name;
187 },
188 getSid: function(pname) {
189 const pIdx = this.players.findIndex(pl => pl.name == pname);
190 return (pIdx === -1 ? null : this.players[pIdx].sid);
191 },
192 sendSomethingTo: function(to, code, obj, warnDisconnected) {
193 const doSend = (code, obj, sid) => {
194 this.st.conn.send(JSON.stringify(Object.assign(
195 {},
196 {code: code},
197 obj,
198 {target: sid}
199 )));
200 };
201 else if (!!to[0])
202 {
203 to.forEach(pname => {
204 // Challenge with targeted players
205 const targetSid = this.getSid(pname);
206 if (!targetSid)
207 {
208 if (!!warnDisconnected)
209 alert("Warning: " + pname + " is not connected");
210 }
211 else
212 doSend(code, obj, targetSid);
213 });
214 }
215 else
216 {
217 // Open challenge: send to all connected players (except us)
218 this.players.forEach(p => {
219 if (p.sid != this.st.user.sid) //only sid is always set
220 doSend(code, obj, p.sid);
221 });
222 }
223 },
224 // Messaging center:
225 socketMessageListener: function(msg) {
226 // Save and call current st.conn.onmessage if one was already defined
227 // --> also needed in future Game.vue (also in Chat.vue component)
228 this.oldOnmessage(msg);
229 const data = JSON.parse(msg.data);
230 switch (data.code)
231 {
232 // 0.2] Receive clients list (just socket IDs)
233 case "pollclients":
234 {
235 data.sockIds.forEach(sid => {
236 this.players.push({sid:sid, id:0, name:""});
237 // Ask identity, challenges and game(s)
238 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
239 this.st.conn.send(JSON.stringify({code:"askchallenges", target:sid}));
240 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
241 });
242 break;
243 }
244 case "askidentity":
245 {
246 // Request for identification: reply if I'm not anonymous
247 if (this.st.user.id > 0)
248 {
249 this.st.conn.send(JSON.stringify(
250 {code:"identity", user:this.st.user, target:data.from}));
251 }
252 break;
253 }
254 case "askchallenge":
255 {
256 // Send my current live challenge (if any)
257 const cIdx = this.challenges
258 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
259 if (cIdx >= 0)
260 {
261 const c = this.challenges[cIdx];
262 const myChallenge =
263 {
264 // Minimal challenge informations: (from not required)
265 to: c.to,
266 fen: c.fen,
267 vid: c.vid,
268 timeControl: c.timeControl
269 };
270 this.st.conn.send(JSON.stringify({code:"challenge",
271 challenge:myChallenge, target:data.from}));
272 }
273 break;
274 }
275 case "askgame":
276 {
277 // TODO: Send my current live game (if any): variant, players, movesCount
278 break;
279 }
280 case "identity":
281 {
282 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
283 this.players[pIdx].id = data.user.id;
284 this.players[pIdx].name = data.user.name;
285 break;
286 }
287 case "challenge":
288 {
289 // Receive challenge from some player (+sid)
290 let newChall = data.chall;
291 newChall.type = this.classifyChallenge(data.chall);
292 const pIdx = this.players.findIndex(p => p.sid == data.from);
293 newChall.from = this.players[pIdx]; //may be anonymous
294 newChall.added = Date.now();
295 newChall.vname = this.getVname(newChall.vid);
296 this.challenges.push(newChall);
297 break;
298 }
299 case "game":
300 {
301 // Receive game from some player (+sid)
302 // TODO: receive game summary (update, count moves)
303 // (just players names, time control, and ID + player ID)
304 // NOTE: it may be correspondance (if newgame while we are connected)
305 break;
306 }
307 // * - receive "new game": if live, store locally + redirect to game
308 // * If corr: notify "new game has started", give link, but do not redirect
309 case "newgame":
310 {
311 // TODO: new game just started: data contain all informations
312 // (id, players, time control, fenStart ...)
313 // + cid to remove challenge from list
314 break;
315 }
316 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
317 // NOTE: challenge "socket" actions accept+withdraw only for live challenges
318 case "acceptchallenge":
319 {
320 // Someone accept an open (or targeted) challenge
321 // TODO: keep SIDs, since we need them to notify newgame after chall is complete
322 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
323 let c = this.challenges[cIdx];
324 if (!c.seats)
325 c.seats = [...Array(c.to.length)];
326 const pIdx = this.players.findIndex(p => p.sid == data.from);
327 // Put this player in the first empty seat we find:
328 let sIdx = 0;
329 for (; sIdx<c.seats.length; sIdx++)
330 {
331 if (!c.seats[sIdx])
332 {
333 c.seats[sIdx] = this.players[pIdx];
334 break;
335 }
336 }
337 if (sIdx == c.seats.length - 1)
338 {
339 // All seats are taken: game can start
340 this.launchGame(c);
341 }
342 break;
343 }
344 case "withdrawchallenge":
345 {
346 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
347 let seats = this.challenges[cIdx].seats;
348 const sIdx = seats.findIndex(s => s.sid == data.sid);
349 seats[sIdx] = undefined;
350 break;
351 }
352 case "refusechallenge":
353 {
354 // TODO: show "player XXX refused challenge", and
355 // remove challenge from list.
356 break;
357 }
358 case "deletechallenge":
359 {
360 ArrayFun.remove(this.challenges, c => c.id == data.cid);
361 break;
362 }
363 // TODO: distinguish hallConnect and gameConnect?
364 // Or (better) global variable players + game variable: "observers"
365 case "connect":
366 // * - receive "player connect": send our current challenge (to him or global)
367 // * Also send all our games (live - max 1 - and corr) [in web worker ?]
368 {
369 this.players.push({name:"", id:0, sid:data.sid});
370 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
371 break;
372 }
373 // * - receive "player disconnect": remove from players list
374 case "disconnect":
375 {
376 ArrayFun.remove(this.players, p => p.sid == data.sid);
377 // Also remove all challenges sent by this player:
378 for (let cIdx = this.challenges.length-1; cIdx >= 0; cIdx--)
379 {
380 if (this.challenges[cIdx].from.sid == data.sid)
381 this.challenges.splice(cIdx, 1);
382 }
383 // and all live games where he plays and no other opponent is online
384 // TODO
385 break;
386 }
387 }
388 },
389 // Challenge lifecycle:
390 tryChallenge: function(player) {
391 if (player.id == 0)
392 return; //anonymous players cannot be challenged
393 this.newchallenge.to[0] = player.name;
394 doClick("modalNewgame");
395 },
396 newChallenge: async function() {
397 const vname = this.getVname(this.newchallenge.vid);
398 const vModule = await import("@/variants/" + vname + ".js");
399 window.V = vModule.VariantRules;
400 const error = checkChallenge(this.newchallenge);
401 if (!!error)
402 return alert(error);
403 const ctype = this.classifyChallenge(this.newchallenge);
404 const cto = this.newchallenge.to.slice(0, this.newchallenge.nbPlayers);
405 // NOTE: "from" information is not required here
406 let chall =
407 {
408 fen: this.newchallenge.fen,
409 to: cto,
410 timeControl: this.newchallenge.timeControl,
411 vid: this.newchallenge.vid,
412 };
413 const finishAddChallenge = (cid) => {
414 chall.id = cid || "c" + getRandString();
415 // Send challenge to peers
416 this.sendSomethingTo(cto, "challenge", {chall:chall}, "warnDisconnected");
417 chall.added = Date.now();
418 chall.type = ctype;
419 chall.vname = vname;
420 chall.from = this.st.user;
421 this.challenges.push(chall);
422 document.getElementById("modalNewgame").checked = false;
423 };
424 const cIdx = this.challenges.findIndex(
425 c => c.from.sid == this.st.user.sid && c.type == ctype);
426 if (cIdx >= 0)
427 {
428 // Delete current challenge (will be replaced now)
429 this.sendSomethingTo(this.challenges[cIdx].to,
430 "deletechallenge", {cid:this.challenges[cIdx].id});
431 if (ctype == "corr")
432 {
433 ajax(
434 "/challenges",
435 "DELETE",
436 {id: this.challenges[cIdx].id}
437 );
438 }
439 this.challenges.splice(cIdx, 1);
440 }
441 if (ctype == "live")
442 {
443 // Live challenges have a random ID
444 finishAddChallenge();
445 }
446 else
447 {
448 // Correspondance game: send challenge to server
449 ajax(
450 "/challenges",
451 "POST",
452 chall,
453 response => { finishAddChallenge(response.cid); }
454 );
455 }
456 },
457 // * - accept challenge (corr or live) --> send info to challenge creator
458 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
459 // * - withdraw from challenge (if >= 3 players and previously accepted)
460 // * --> send info to challenge creator
461 // * - refuse challenge: send "refuse" to challenge sender, and "delete" to others
462 // * - prepare and start new game (if challenge is full after acceptation)
463 // * --> include challenge ID (so that opponents can delete the challenge too)
464 clickChallenge: function(c) {
465 // TODO: also correspondance case (send to server)
466 if (!!c.accepted)
467 {
468 // It's a multiplayer challenge I accepted: withdraw
469 this.st.conn.send(JSON.stringify({code: "withdrawchallenge",
470 cid: c.id, target: c.from.sid}));
471 c.accepted = false;
472 }
473 else if (c.from.sid == this.st.user.sid) //it's my challenge: cancel it
474 {
475 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
476 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
477 }
478 else //accept (or refuse) a challenge
479 {
480 c.accepted = true;
481 if (!!c.to[0])
482 {
483 // TODO: if special FEN, show diagram after loading variant
484 c.accepted = confirm("Accept challenge?");
485 }
486 this.st.conn.send(JSON.stringify({
487 code: (c.accepted ? "accept" : "refuse") + "challenge",
488 cid: c.id, target: c.from.sid}));
489 if (!c.accepted)
490 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
491 }
492 },
493 launchGame: function(c) {
494 // Just assign colors and pass the message
495 const vname = this.getVname(c.vid);
496 const vModule = await import("@/variants/" + vname + ".js");
497 window.V = vModule.VariantRules;
498 let players = [c.from];
499 Array.prototype.push.apply(players, c.seats);
500 c.type == corr alors use id...sinon sid (figés)
501 let gameInfo =
502 {
503 cid: c.id, //required to remove challenge
504 fen: c.fen || V.GenRandInitFen(),
505 // Shuffle players order (white then black then other colors).
506 // Players' names are not required
507 players: shuffle(players).map(p => {id:p.id, sid:p.sid},
508 vid: c.vid,
509 timeControl: c.timeControl,
510 };
511 c.seats.forEach(s => {
512 this.st.conn.send(JSON.stringify({code:"newgame",
513 gameInfo:gameInfo, target:s.sid}));
514 });
515 this.newGame(gameInfo); //also!
516 },
517 newGame: function(gameInfo) {
518 // Extract times (in [milli?]seconds), set clocks,
519 // store in localStorage if live (on server otherwise)
520 // const fen = chall.fen || V.GenRandInitFen();
521 // const game = {}; //TODO: fen, players, time ...
522 // //setStorage(game); //TODO
523 // game.players.forEach(p => { //...even if game is by corr (could be played live, why not...)
524 // this.conn.send(
525 // JSON.stringify({code:"newgame", oppid:p.id, game:game}));
526 // });
527 // if (this.settings.sound >= 1)
528 // new Audio("/sounds/newgame.mp3").play().catch(err => {});
529 },
530 },
531 };
532 </script>
533
534 <style lang="sass">
535 // TODO
536 </style>