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