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