Small advance on Hall.vue (challenges + display)
[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-5.col-md-offset-1.col-lg-4.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" checked aria-hidden="true" name="accordion")
50 label(for="peopleSection" aria-hidden="true") People
51 div
52 #players(v-show="pdisplay=='players'")
53 h3 Online players
54 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
55 :class="{anonymous: !!p.count}"
56 )
57 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
58 #chat(v-show="pdisplay=='chat'")
59 h3 Chat (TODO)
60 input#gameSection(type="radio" checked aria-hidden="true" name="accordion")
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")
70 </template>
71
72 <script>
73 import { store } from "@/store";
74 import { NbPlayers } from "@/data/nbPlayers";
75 import { checkChallenge } from "@/data/challengeCheck";
76 import { ArrayFun } from "@/utils/array";
77 import { ajax } from "@/utils/ajax";
78 import { getRandString } from "@/utils/alea";
79 import GameList from "@/components/GameList.vue";
80 import ChallengeList from "@/components/ChallengeList.vue";
81 export default {
82 name: "my-hall",
83 components: {
84 GameList,
85 ChallengeList,
86 },
87 data: function () {
88 return {
89 st: store.state,
90 cdisplay: "live", //or corr
91 pdisplay: "players", //or chat
92 gdisplay: "live",
93 games: [],
94 challenges: [],
95 players: [], //online players
96 newchallenge: {
97 fen: "",
98 vid: 0,
99 nbPlayers: 0,
100 to: ["", "", ""], //name of challenged players
101 timeControl: "", //"2m+2s" ...etc
102 },
103 };
104 },
105 computed: {
106 uniquePlayers: function() {
107 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
108 let anonymous = {id:0, name:"@nonymous", count:0};
109 let playerList = [];
110 this.players.forEach(p => {
111 if (p.id > 0)
112 playerList.push(p);
113 else
114 anonymous.count++;
115 });
116 if (anonymous.count > 0)
117 playerList.push(anonymous);
118 return playerList;
119 },
120 },
121 created: function() {
122 // Always add myself to players' list
123 this.players.push(this.st.user);
124 // Ask server for current corr games (all but mines)
125 // ajax(
126 // "",
127 // "GET",
128 // response => {
129 //
130 // }
131 // );
132 // // Also ask for corr challenges (all)
133 // ajax(
134 // "",
135 // "GET",
136 // response => {
137 //
138 // }
139 // );
140 // 0.1] Ask server for for room composition:
141 const socketOpenListener = () => {
142 this.st.conn.send(JSON.stringify({code:"pollclients"}));
143 };
144 this.st.conn.onopen = socketOpenListener;
145 // TODO: is this required here?
146 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
147 this.st.conn.onmessage = this.socketMessageListener;
148 const oldOnclose = this.st.conn.onclose;
149 const socketCloseListener = () => {
150 oldOnclose(); //reinitialize connexion (in store.js)
151 this.st.conn.addEventListener('message', this.socketMessageListener);
152 this.st.conn.addEventListener('close', socketCloseListener);
153 };
154 this.st.conn.onclose = socketCloseListener;
155 },
156 methods: {
157 filterChallenges: function(type) {
158 return this.challenges.filter(c => c.type == type);
159 },
160 filterGames: function(type) {
161 return this.games.filter(c => c.type == type);
162 },
163 classifyChallenge: function(c) {
164 // Heuristic: should work for most cases... (TODO)
165 return (c.timeControl.indexOf('d') === -1 ? "live" : "corr");
166 },
167 socketMessageListener: function(msg) {
168 // Save and call current st.conn.onmessage if one was already defined
169 // --> also needed in future Game.vue (also in Chat.vue component)
170 this.oldOnmessage(msg);
171 const data = JSON.parse(msg.data);
172 switch (data.code)
173 {
174 // 0.2] Receive clients list (just socket IDs)
175 case "pollclients":
176 data.sockIds.forEach(sid => {
177 this.players.push({sid:sid, id:0, name:""});
178 // Ask identity, challenges and game(s)
179 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
180 this.st.conn.send(JSON.stringify({code:"askchallenges", target:sid}));
181 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
182 });
183 break;
184 case "askidentity":
185 // Request for identification: reply if I'm not anonymous
186 if (this.st.user.id > 0)
187 {
188 this.st.conn.send(JSON.stringify(
189 {code:"identity", user:this.st.user, target:data.from}));
190 }
191 break;
192 case "askchallenge":
193 // Send my current live challenge (if any)
194 const cIdx = this.challenges
195 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
196 if (cIdx >= 0)
197 {
198 const c = this.challenges[cIdx];
199 const myChallenge =
200 {
201 // Minimal challenge informations: (from not required)
202 to: c.to,
203 fen: c.fen,
204 vid: c.vid,
205 timeControl: c.timeControl
206 };
207 this.st.conn.send(JSON.stringify({code:"challenge",
208 challenge:myChallenge, target:data.from})
209 }
210 break;
211 case "askgame":
212 // TODO: Send my current live game (if any): variant, players, movesCount
213 break;
214 case "identity":
215 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
216 this.players[pIdx].id = data.user.id;
217 this.players[pIdx].name = data.user.name;
218 break;
219 case "challenge":
220 // Receive challenge from some player (+sid)
221 let newChall = data.chall;
222 newChall.type = classifyChallenge(data.chall);
223 const pIdx = this.players.findIndex(p => p.sid == data.sid);
224 newChall.from = this.players[pIdx]; //may be anonymous
225 this.challenges.push(newChall);
226 break;
227 case "game":
228 // Receive game from some player (+sid)
229 // TODO: receive game summary (update, count moves)
230 // (just players names, time control, and ID + player ID)
231 // NOTE: it may be correspondance (if newgame while we are connected)
232 break;
233 // * - receive "new game": if live, store locally + redirect to game
234 // * If corr: notify "new game has started", give link, but do not redirect
235 case "newgame":
236 // TODO: new game just started: data contain all informations
237 // (id, players, time control, fenStart ...)
238 // + cid to remove challenge from list
239 break;
240 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
241 case "acceptchallenge":
242 // someone accept an open (or targeted) challenge
243 // ==> if (open and) full and I don't play, delete from list
244 // If I play: just add player. Then, if full send a "newgame"
245 // and (if full) in any case, remove challenge from list.
246 if (this.challenges.some(c => c.id == data.cid) //.............TODO
247 this.newGame(data.challenge, data.user); //user.id et user.name
248 break;
249 case "withdrawchallenge":
250 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
251 let chall = this.challenges[cIdx]
252 ArrayFun.remove(chall.players, p => p.id == data.uid);
253 chall.players.push({id:0, name:""});
254 break;
255 case "cancelchallenge":
256 ArrayFun.remove(this.challenges, c => c.id == data.cid);
257 break;
258 // TODO: distinguish hallConnect and gameConnect ?
259 // Or global variable players
260 // + game variable: "observers"
261 case "connect":
262 // * - receive "player connect": send our current challenge (to him or global)
263 // * Also send all our games (live - max 1 - and corr) [in web worker ?]
264 this.players.push({name:"", id:0, sid:data.sid});
265 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
266 break;
267 // * - receive "player disconnect": remove from players list
268 case "disconnect":
269 ArrayFun.remove(this.players, p => p.sid == data.sid);
270 // TODO: also remove all challenges sent by this player,
271 // and all live games where he plays and no other opponent is online
272 break;
273 }
274 },
275 showGame: function(game) {
276 // NOTE: if we are an observer, the game will be found in main games list
277 // (sent by connected remote players)
278 // TODO: game path ? /vname/gameId seems better
279 this.$router.push("/" + game.id);
280 },
281 tryChallenge: function(player) {
282 if (player.id == 0)
283 return; //anonymous players cannot be challenged
284 this.newchallenge.to[0] = player.name;
285 doClick("modalNewgame");
286 },
287 // * - accept challenge (corr or live) --> send info to all concerned players
288 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
289 // * - withdraw from challenge (if >= 3 players and previously accepted)
290 // * --> send info to all concerned players
291 // * - refuse challenge (or receive refusal): send to all challenge players (from + to)
292 // * except us ; graphics: modal again ? (inline ?)
293 // * - prepare and start new game (if challenge is full after acceptation)
294 // * --> include challenge ID (so that opponents can delete the challenge too)
295 // * Also send to all connected players (only from me)
296 clickChallenge: function(challenge) {
297 // TODO: also correspondance case (send to server)
298 const index = this.challenges.findIndex(c => c.id == challenge.id);
299 const toIdx = challenge.to.findIndex(name => name == this.st.user.name);
300 if (toIdx >= 0)
301 {
302 // It's a multiplayer challenge I accepted: withdraw
303 this.st.conn.send(JSON.stringify({code:"withdrawchallenge",
304 cid:challenge.id, user:this.st.user.sid}));
305 this.challenges.to.splice(toIdx, 1);
306 }
307 else if (challenge.from.id == user.id) //it's my challenge: cancel it
308 {
309 this.st.conn.send(JSON.stringify({code:"cancelchallenge", cid:challenge.id}));
310 this.challenges.splice(index, 1);
311 }
312 else //accept a challenge
313 {
314 this.st.conn.send(JSON.stringify({code:"acceptchallenge",
315 cid:challenge.id, user:me}));
316 this.challenges[index].to.push(me);
317 }
318 // TODO: accepter un challenge peut lancer une partie, il
319 // faut alors supprimer challenge + creer partie + la retourner et l'ajouter ici
320 // si pas le mien et FEN speciale :: (charger code variante et)
321 // montrer diagramme + couleur (orienté)
322 },
323 // user: last person to accept the challenge (TODO: revoir ça)
324 // newGame: function(chall, user) {
325 // const fen = chall.fen || V.GenRandInitFen();
326 // const game = {}; //TODO: fen, players, time ...
327 // //setStorage(game); //TODO
328 // game.players.forEach(p => { //...even if game is by corr (could be played live, why not...)
329 // this.conn.send(
330 // JSON.stringify({code:"newgame", oppid:p.id, game:game}));
331 // });
332 // if (this.settings.sound >= 1)
333 // new Audio("/sounds/newgame.mp3").play().catch(err => {});
334 // },
335 // Load a variant file (TODO: should probably be global)
336 loadVariant: async function(vid, variantArray) {
337 const idxInVariants = variantArray.findIndex(v => v.id == vid);
338 const vname = variantArray[idxInVariants].name;
339 const vModule = await import("@/variants/" + vname + ".js");
340 window.V = vModule.VariantRules;
341 return vname;
342 },
343 // Send new challenge (corr or live, cf. time control), with button or click on player
344 newChallenge: async function() {
345 // TODO: put this "load variant" block elsewhere
346 const vname = this.loadVariant(this.newchallenge.vid, this.st.variants);
347 // checkChallenge side-effect = , and mainTime + increment in seconds
348 // TODO: should not be a side-effect but set here ; for received server challenges we do not have mainTime+increment
349 const error = checkChallenge(this.newchallenge);
350 if (!!error)
351 return alert(error);
352 if (this.challenges.some(c => c.from.sid == this.st.user.sid && c.liveGame))
353 {
354 document.getElementById("modalNewgame").checked = false;
355 return alert("You already have a pending live challenge");
356 // TODO: better to just replace current challenge
357 // --> also for corr challenges
358 }
359 // Check that the players (if any indicated) are online
360 let chall = Object.Assign(
361 {},
362 this.newchallenge,
363 {
364 from: this.st.user,
365 added: Date.now(),
366 fen: this.newchallenge.fen || V.GenRandInitFen(),
367 variant: {id: this.newchallenge.vid, name: vname},
368 nbPlayers: this.newchallenge.nbPlayers,
369 to: [
370 {id: 0, name: this.newchallenge.to[0], sid: ""},
371 {id: 0, name: this.newchallenge.to[1], sid: ""},
372 {id: 0, name: this.newchallenge.to[2], sid: ""},
373 ],
374 timeControl: this.newchallenge.timeControl,
375 };
376 for (let p of chall.to)
377 {
378 if (p.name != "")
379 {
380 const pIdx = this.players.findIndex(pl => pl.name == p.name);
381 // NOTE: id (server DB) and sid (socket ID).
382 // Anonymous players just have a socket ID.
383 // NOTE: for correspondance play we don't require players to be online
384 // (==> we don't have IDs, and no sid)
385 if (liveGame && pIdx === -1)
386 return alert(p.name + " is not connected");
387 p.id = this.players[pIdx].id;
388 p.sid = this.players[pIdx].sid;
389 }
390 }
391 const finishAddChallenge = (cid) => {
392 chall.id = cid || "c" + getRandString();
393 this.challenges.push(chall);
394 // Send challenge to peers
395 let challSock =
396 {
397 code: "newchallenge",
398 chall: chall,
399 target: "",
400 };
401 const sendChallengeTo = (sid) => {
402 challSock.target = sid;
403 this.st.conn.send(JSON.stringify(challSock));
404 };
405 if (chall.to[0].id > 0)
406 {
407 // Challenge with targeted players
408 chall.to.forEach(p => {
409 if (p.id > 0)
410 sendChallengeTo(p.sid);
411 });
412 }
413 else
414 {
415 // Open challenge: send to all connected players (except us)
416 this.players.forEach(p => {
417 if (p.sid != this.st.user.sid) //only sid is always set
418 sendChallengeTo(p.sid);
419 });
420 }
421 document.getElementById("modalNewgame").checked = false;
422 };
423 if (this.newchallenge.liveGame)
424 {
425 // Live challenges have cid = 0
426 finishAddChallenge();
427 }
428 else
429 {
430 const chall = {
431 uid: req.body["from"],
432 vid: req.body["vid"],
433 fen: req.body["fen"],
434 timeControl: req.body["timeControl"],
435 nbPlayers: req.body["nbPlayers"],
436 to: req.body["to"], //array of IDs
437 };
438 // Correspondance game: send challenge to server
439 ajax(
440 "/challenges/" + this.newchallenge.vid,
441 "POST",
442 chall,
443 response => {
444 chall.id = response.cid;
445 finishAddChallenge();
446 }
447 );
448 }
449 },
450 possibleNbplayers: function(nbp) {
451 if (this.newchallenge.vid == 0)
452 return false;
453 const variants = this.st.variants;
454 const idxInVariants =
455 variants.findIndex(v => v.id == this.newchallenge.vid);
456 return NbPlayers[variants[idxInVariants].name].includes(nbp);
457 },
458 },
459 };
460 </script>
461
462 <style lang="sass">
463 // TODO
464 </style>