Some advances in challenge handling (server+client)
[vchess.git] / client / src / views / Hall.vue
1 <!-- Main playing hall: online players + current challenges + button "new game" -->
2
3 <template lang="pug">
4 main
5 input#modalNewgame.modal(type="checkbox")
6 div(role="dialog" aria-labelledby="titleFenedit")
7 .card.smallpad
8 label#closeNewgame.modal-close(for="modalNewgame")
9 fieldset
10 label(for="selectVariant") {{ st.tr["Variant"] }}
11 select#selectVariant(v-model="newchallenge.vid")
12 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
13 fieldset
14 label(for="selectNbPlayers") {{ st.tr["Number of players"] }}
15 select#selectNbPlayers(v-model="newchallenge.nbPlayers")
16 option(v-show="possibleNbplayers(2)" value="2") 2
17 option(v-show="possibleNbplayers(3)" value="3") 3
18 option(v-show="possibleNbplayers(4)" value="4") 4
19 fieldset
20 label(for="timeControl") {{ st.tr["Time control"] }}
21 input#timeControl(type="text" v-model="newchallenge.timeControl"
22 placeholder="3m+2s, 1h+30s, 7d+1d ...")
23 fieldset(v-if="st.user.id > 0")
24 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
25 #selectPlayers
26 input(type="text" v-model="newchallenge.to[0].name")
27 input(v-show="newchallenge.nbPlayers>=3" type="text"
28 v-model="newchallenge.to[1].name")
29 input(v-show="newchallenge.nbPlayers==4" type="text"
30 v-model="newchallenge.to[2].name")
31 fieldset(v-if="st.user.id > 0")
32 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
33 input#inputFen(type="text" v-model="newchallenge.fen")
34 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
35 .row
36 .col-sm-12.col-md-5.col-md-offset-1.col-lg-4.col-lg-offset-2
37 .button-group
38 button(@click="cpdisplay='challenges'") Challenges
39 button(@click="cpdisplay='players'") Players
40 ChallengeList(v-show="cpdisplay=='challenges'"
41 :challenges="challenges" @click-challenge="clickChallenge")
42 #players(v-show="cpdisplay=='players'")
43 h3 Online players
44 div(v-for="p in uniquePlayers" @click="tryChallenge(p)")
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:"askclients"}));
131 };
132 this.st.conn.onopen = socketOpenListener;
133 this.oldOnmessage = this.st.conn.onmessage || Function.prototype; //TODO: required here?
134 this.st.conn.onmessage = this.socketMessageListener;
135 const oldOnclose = this.st.conn.onclose;
136 const socketCloseListener = () => {
137 oldOnclose(); //reinitialize connexion (in store.js)
138 this.st.conn.addEventListener('message', this.socketMessageListener);
139 this.st.conn.addEventListener('close', socketCloseListener);
140 };
141 this.st.conn.onclose = socketCloseListener;
142 },
143 methods: {
144 socketMessageListener: function(msg) {
145 // Save and call current st.conn.onmessage if one was already defined
146 // --> also needed in future Game.vue (also in Chat.vue component)
147 // TODO: merge Game.vue and MoveList.vue (one logic entity, no ?)
148 this.oldOnmessage(msg);
149 const data = JSON.parse(msg.data);
150 switch (data.code)
151 {
152 // 0.2] Receive clients list (just socket IDs)
153 case "clients":
154 data.sockIds.forEach(sid => {
155 this.players.push({sid:sid, id:0, name:""});
156 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
157 });
158 break;
159 // TODO: also receive "askchallenges", "askgames"
160 case "identify":
161 // Request for identification
162 this.st.conn.send(JSON.stringify(
163 {code:"identity", user:this.st.user, target:data.from}));
164 break;
165 case "identity":
166 if (data.user.id > 0) //otherwise "anonymous", nothing to retrieve
167 {
168 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
169 this.players[pIdx].id = data.user.id;
170 this.players[pIdx].name = data.user.name;
171 }
172 break;
173 // * - receive "new game": if live, store locally + redirect to game
174 // * If corr: notify "new game has started", give link, but do not redirect
175 case "newgame":
176 // TODO: new game just started: data contain all informations
177 // (id, players, time control, fenStart ...)
178 // + cid to remove challenge from list
179 break;
180 // * - receive "playergame": a live game by some connected player (NO corr)
181 case "playergame":
182 // TODO: receive live game summary (update, count moves)
183 // (just players names, time control, and ID + player ID)
184 break;
185 // * - receive "playerchallenges": list of challenges (sent) by some online player (NO corr)
186 case "playerchallenges":
187 // TODO: receive challenge + challenge updates
188 break;
189 case "newmove": //live or corr
190 // TODO: name conflict ? (game "newmove" event)
191 break;
192 // * - receive new challenge: if targeted, replace our name with sender name
193 case "newchallenge":
194 // receive live or corr challenge
195 this.challenges.push(data.chall);
196 break;
197 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
198 case "acceptchallenge":
199 if (true) //TODO: if challenge is full
200 this.newGame(data.challenge, data.user); //user.id et user.name
201 break;
202 case "withdrawchallenge":
203 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
204 let chall = this.challenges[cIdx]
205 ArrayFun.remove(chall.players, p => p.id == data.uid);
206 chall.players.push({id:0, name:""});
207 break;
208 case "cancelchallenge":
209 ArrayFun.remove(this.challenges, c => c.id == data.cid);
210 break;
211 // NOTE: finally only one connect / disconnect couple of events
212 // (because on server side we wouldn't know which to choose)
213 case "connect":
214 // * - receive "player connect": send all our current challenges (to him or global)
215 // * Also send all our games (live - max 1 - and corr) [in web worker ?]
216 // * + all our sent challenges.
217 this.players.push({name:"", id:0, sid:data.sid});
218 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
219 // TODO: si on est en train de jouer une partie, le notifier au nouveau connecté
220 // envoyer aussi nos défis
221 break;
222 // * - receive "player disconnect": remove from players list
223 case "disconnect":
224 ArrayFun.remove(this.players, p => p.sid == data.sid);
225 // TODO: also remove all challenges sent by this player,
226 // and all live games where he plays and no other opponent is online
227 break;
228 }
229 },
230 showGame: function(game) {
231 // NOTE: if we are an observer, the game will be found in main games list
232 // (sent by connected remote players)
233 // TODO: game path ? /vname/gameId seems better
234 this.$router.push("/" + game.id)
235 },
236 tryChallenge: function(player) {
237 if (player.id == 0)
238 return; //anonymous players cannot be challenged
239 this.newchallenge.players[0] = {
240 name: player.name,
241 id: player.id,
242 sid: player.sid,
243 };
244 doClick("modalNewgame");
245 },
246 // * - accept challenge (corr or live) --> send info to all concerned players
247 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
248 // * - withdraw from challenge (if >= 3 players and previously accepted)
249 // * --> send info to all concerned players
250 // * - refuse challenge (or receive refusal): send to all challenge players (from + to)
251 // * except us ; graphics: modal again ? (inline ?)
252 // * - prepare and start new game (if challenge is full after acceptation)
253 // * --> include challenge ID (so that opponents can delete the challenge too)
254 // * Also send to all connected players (only from me)
255 clickChallenge: function(challenge) {
256 const index = this.challenges.findIndex(c => c.id == challenge.id);
257 const toIdx = challenge.to.findIndex(p => p.id == user.id);
258 const me = {name:user.name,id:user.id};
259 if (toIdx >= 0)
260 {
261 // It's a multiplayer challenge I accepted: withdraw
262 this.st.conn.send(JSON.stringify({code:"withdrawchallenge",
263 cid:challenge.id, user:me}));
264 this.challenges.to.splice(toIdx, 1);
265 }
266 else if (challenge.from.id == user.id) //it's my challenge: cancel it
267 {
268 this.st.conn.send(JSON.stringify({code:"cancelchallenge", cid:challenge.id}));
269 this.challenges.splice(index, 1);
270 }
271 else //accept a challenge
272 {
273 this.st.conn.send(JSON.stringify({code:"acceptchallenge",
274 cid:challenge.id, user:me}));
275 this.challenges[index].to.push(me);
276 }
277 // TODO: accepter un challenge peut lancer une partie, il
278 // faut alors supprimer challenge + creer partie + la retourner et l'ajouter ici
279 // si pas le mien et FEN speciale :: (charger code variante et)
280 // montrer diagramme + couleur (orienté)
281 },
282 // user: last person to accept the challenge (TODO: revoir ça)
283 // newGame: function(chall, user) {
284 // const fen = chall.fen || V.GenRandInitFen();
285 // const game = {}; //TODO: fen, players, time ...
286 // //setStorage(game); //TODO
287 // game.players.forEach(p => { //...even if game is by corr (could be played live, why not...)
288 // this.conn.send(
289 // JSON.stringify({code:"newgame", oppid:p.id, game:game}));
290 // });
291 // if (this.settings.sound >= 1)
292 // new Audio("/sounds/newgame.mp3").play().catch(err => {});
293 // },
294 // Load a variant file (TODO: should probably be global)
295 loadVariant: async function(vid, variantArray) {
296 const idxInVariants = variantArray.findIndex(v => v.id == vid);
297 const vname = variantArray[idxInVariants].name;
298 const vModule = await import("@/variants/" + vname + ".js");
299 window.V = vModule.VariantRules;
300 return vname;
301 },
302 // Send new challenge (corr or live, cf. time control), with button or click on player
303 newChallenge: async function() {
304 if (this.challenges.some(c => c.from.sid == this.st.user.sid))
305 {
306 document.getElementById("modalNewgame").checked = false;
307 return alert("You already have a pending challenge");
308 }
309 // TODO: put this "load variant" block elsewhere
310 const vname = this.loadVariant(this.newchallenge.vid, this.st.variants);
311 // checkChallenge side-effect = set FEN, and mainTime + increment in seconds
312 // TODO: should not be a side-effect but set here ; for received server challenges we do not have mainTime+increment
313 const error = checkChallenge(this.newchallenge);
314 if (!!error)
315 return alert(error);
316 // TODO: set FEN, set mainTime and increment ?!
317 //else //generate a FEN
318 // c.fen = V.GenRandInitFen();
319 // Less than 3 days ==> live game (TODO: heuristic... 40 moves also)
320 const liveGame =
321 this.newchallenge.mainTime + 40 * this.newchallenge.increment < 3*24*60*60;
322 // Check that the players (if any indicated) are online
323 let chall =
324 {
325 id: 0, //unknown yet (no ID for live challenges)
326 from: this.st.user,
327 added: Date.now(),
328 fen: this.newchallenge.fen,
329 variant: {id: this.newchallenge.vid, name: vname},
330 nbPlayers: this.newchallenge.nbPlayers,
331 to: [
332 {id: 0, name: this.newchallenge.to[0], sid: ""},
333 {id: 0, name: this.newchallenge.to[1], sid: ""},
334 {id: 0, name: this.newchallenge.to[2], sid: ""},
335 ],
336 timeControl: this.newchallenge.timeControl,
337 mainTime: this.newchallenge.mainTime,
338 increment: this.newchallenge.increment,
339 };
340 for (let p of chall.to)
341 {
342 if (p.name != "")
343 {
344 const pIdx = this.players.findIndex(pl => pl.name == p.name);
345 // NOTE: id (server DB) and sid (socket ID).
346 // Anonymous players just have a socket ID.
347 // NOTE: for correspondance play we don't require players to be online
348 // (==> we don't have IDs, and no sid)
349 if (liveGame && pIdx === -1)
350 return alert(p.name + " is not connected");
351 p.id = this.players[pIdx].id;
352 p.sid = this.players[pIdx].sid;
353 }
354 }
355 const finishAddChallenge = (cid) => {
356 chall.id = cid || "c" + getRandString();
357 this.challenges.push(chall);
358 // Send challenge to peers
359 let challSock =
360 {
361 code: "newchallenge",
362 chall: chall,
363 target: "",
364 };
365 const sendChallengeTo = (sid) => {
366 challSock.target = sid;
367 this.st.conn.send(JSON.stringify(challSock));
368 };
369 if (chall.to[0].id > 0)
370 {
371 // Challenge with targeted players
372 chall.to.forEach(p => {
373 if (p.id > 0)
374 sendChallengeTo(p.sid);
375 });
376 }
377 else
378 {
379 // Open challenge: send to all connected players (except us)
380 this.players.forEach(p => {
381 if (p.sid != this.st.user.sid) //only sid is always set
382 sendChallengeTo(p.sid);
383 });
384 }
385 document.getElementById("modalNewgame").checked = false;
386 };
387 if (liveGame)
388 {
389 // Live challenges have cid = 0
390 finishAddChallenge();
391 }
392 else
393 {
394 const chall = {
395 uid: req.body["from"],
396 vid: req.body["vid"],
397 fen: req.body["fen"],
398 timeControl: req.body["timeControl"],
399 nbPlayers: req.body["nbPlayers"],
400 to: req.body["to"], //array of IDs
401 };
402 // Correspondance game: send challenge to server
403 ajax(
404 "/challenges/" + this.newchallenge.vid,
405 "POST",
406 chall,
407 response => {
408 chall.id = response.cid;
409 finishAddChallenge();
410 }
411 );
412 }
413 },
414 possibleNbplayers: function(nbp) {
415 if (this.newchallenge.vid == 0)
416 return false;
417 const variants = this.st.variants;
418 const idxInVariants =
419 variants.findIndex(v => v.id == this.newchallenge.vid);
420 return NbPlayers[variants[idxInVariants].name].includes(nbp);
421 },
422 },
423 };
424 </script>
425
426 <style lang="sass">
427 // TODO
428 </style>