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