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