Save state (nothing really achieved)
[vchess.git] / client / src / views / Hall.vue
... / ...
CommitLineData
1<!-- Main playing hall: online players + current challenges + button "new game" -->
2
3<template lang="pug">
4main
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>
61import { store } from "@/store";
62import { NbPlayers } from "@/data/nbPlayers";
63import { checkChallenge } from "@/data/challengeCheck";
64import { ArrayFun } from "@/utils/array";
65import { ajax } from "@/utils/ajax";
66import GameList from "@/components/GameList.vue";
67import ChallengeList from "@/components/ChallengeList.vue";
68export default {
69 name: "my-hall",
70 components: {
71 GameList,
72 ChallengeList,
73 },
74 data: function () {
75 return {
76 st: store.state,
77 cpdisplay: "challenges",
78 gdisplay: "live",
79 liveGames: [],
80 corrGames: [],
81 challenges: [],
82 players: [], //online players
83 newchallenge: {
84 fen: "",
85 vid: 0,
86 nbPlayers: 0,
87 to: ["", "", ""], //name of challenged players
88 timeControl: "", //"2m+2s" ...etc
89 },
90 };
91 },
92 computed: {
93 uniquePlayers: function() {
94 // Show e.g. "5 @nonymous", and do nothing on click on anonymous
95 let anonymous = {id:0, name:"@nonymous", count:0};
96 let playerList = [];
97 this.players.forEach(p => {
98 if (p.id > 0)
99 playerList.push(p);
100 else
101 anonymous.count++;
102 });
103 if (anonymous.count > 0)
104 playerList.push(anonymous);
105 return playerList;
106 },
107 },
108 created: function() {
109 // Always add myself to players' list
110 this.players.push(this.st.user);
111 // TODO: ask server for current corr games (all but mines: names, ID, time control)
112 // also ask for corr challenges
113 // Ask server for for room composition:
114 const socketOpenListener = () => {
115 this.st.conn.send(JSON.stringify({code:"askplayers"}));
116 };
117 this.st.conn.onopen = socketOpenListener;
118 this.st.conn.onmessage = this.socketMessageListener;
119 const socketCloseListener = () => {
120 // connexion is reinitialized in store.js
121 this.st.conn.addEventListener('message', this.socketMessageListener);
122 this.st.conn.addEventListener('close', socketCloseListener);
123 };
124 this.st.conn.onclose = socketCloseListener;
125 },
126 methods: {
127 socketMessageListener: function(msg) {
128 const data = JSON.parse(msg.data);
129 switch (data.code)
130 {
131 case "room":
132 // TODO: receive room composition (sids at least, id + names if registered)
133 // TODO: also receive "askchallenges", "askgames"
134// * - receive "new game": if live, store locally + redirect to game
135// * If corr: notify "new game has started", give link, but do not redirect
136 case "newgame":
137 // TODO: new game just started: data contain all informations
138 // (id, players, time control, fenStart ...)
139 // + cid to remove challenge from list
140 break;
141// * - receive "playergame": a live game by some connected player (NO corr)
142 case "playergame":
143 // TODO: receive live game summary (update, count moves)
144 // (just players names, time control, and ID + player ID)
145 break;
146// * - receive "playerchallenges": list of challenges (sent) by some online player (NO corr)
147 case "playerchallenges":
148 // TODO: receive challenge + challenge updates
149 break;
150 case "newmove": //live or corr
151 // TODO: name conflict ? (game "newmove" event)
152 break;
153// * - receive new challenge: if targeted, replace our name with sender name
154 case "newchallenge":
155 // receive live or corr challenge
156 break;
157// * - receive "accept/withdraw/cancel challenge": apply action to challenges list
158 case "acceptchallenge":
159 if (true) //TODO: if challenge is full
160 this.newGame(data.challenge, data.user); //user.id et user.name
161 break;
162 case "withdrawchallenge":
163 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
164 let chall = this.challenges[cIdx]
165 ArrayFun.remove(chall.players, p => p.id == data.uid);
166 chall.players.push({id:0, name:""});
167 break;
168 case "cancelchallenge":
169 ArrayFun.remove(this.challenges, c => c.id == data.cid);
170 break;
171// NOTE: finally only one connect / disconnect couple of events
172// (because on server side we wouldn't know which to choose)
173 case "connect":
174// * - receive "player connect": send all our current challenges (to him or global)
175// * Also send all our games (live - max 1 - and corr) [in web worker ?]
176// * + all our sent challenges.
177 this.players.push({name:data.name, id:data.uid});
178 // TODO: si on est en train de jouer une partie, le notifier au nouveau connecté
179 // envoyer aussi nos défis
180 break;
181// * - receive "player disconnect": remove from players list
182 case "disconnect":
183 ArrayFun.remove(this.players, p => p.id == data.uid);
184 // TODO: also remove all challenges sent by this player,
185 // and all live games where he plays and no other opponent is online
186 break;
187 }
188 },
189 showGame: function(game) {
190 // NOTE: if we are an observer, the game will be found in main games list
191 // (sent by connected remote players)
192 // TODO: game path ? /vname/gameId seems better
193 this.$router.push("/" + game.id)
194 },
195 tryChallenge: function(player) {
196 if (player.id == 0)
197 return; //anonymous players cannot be challenged
198 this.newchallenge.players[0] = {
199 name: player.name,
200 id: player.id,
201 sid: player.sid,
202 };
203 doClick("modalNewgame");
204 },
205// * - accept challenge (corr or live) --> send info to all concerned players
206// * - cancel challenge (click on sent challenge) --> send info to all concerned players
207// * - withdraw from challenge (if >= 3 players and previously accepted)
208// * --> send info to all concerned players
209// * - refuse challenge (or receive refusal): send to all challenge players (from + to)
210// * except us ; graphics: modal again ? (inline ?)
211// * - prepare and start new game (if challenge is full after acceptation)
212// * --> include challenge ID (so that opponents can delete the challenge too)
213// * Also send to all connected players (only from me)
214 clickChallenge: function(challenge) {
215 const index = this.challenges.findIndex(c => c.id == challenge.id);
216 const toIdx = challenge.to.findIndex(p => p.id == user.id);
217 const me = {name:user.name,id:user.id};
218 if (toIdx >= 0)
219 {
220 // It's a multiplayer challenge I accepted: withdraw
221 this.st.conn.send(JSON.stringify({code:"withdrawchallenge",
222 cid:challenge.id, user:me}));
223 this.challenges.to.splice(toIdx, 1);
224 }
225 else if (challenge.from.id == user.id) //it's my challenge: cancel it
226 {
227 this.st.conn.send(JSON.stringify({code:"cancelchallenge", cid:challenge.id}));
228 this.challenges.splice(index, 1);
229 }
230 else //accept a challenge
231 {
232 this.st.conn.send(JSON.stringify({code:"acceptchallenge",
233 cid:challenge.id, user:me}));
234 this.challenges[index].to.push(me);
235 }
236 // TODO: accepter un challenge peut lancer une partie, il
237 // faut alors supprimer challenge + creer partie + la retourner et l'ajouter ici
238 // si pas le mien et FEN speciale :: (charger code variante et)
239 // montrer diagramme + couleur (orienté)
240 },
241 // user: last person to accept the challenge (TODO: revoir ça)
242// newGame: function(chall, user) {
243// const fen = chall.fen || V.GenRandInitFen();
244// const game = {}; //TODO: fen, players, time ...
245// //setStorage(game); //TODO
246// game.players.forEach(p => { //...even if game is by corr (could be played live, why not...)
247// this.conn.send(
248// JSON.stringify({code:"newgame", oppid:p.id, game:game}));
249// });
250// if (this.settings.sound >= 1)
251// new Audio("/sounds/newgame.mp3").play().catch(err => {});
252// },
253 // Send new challenge (corr or live, cf. time control), with button or click on player
254 newChallenge: async function() {
255 if (this.challenges.some(c => c.from.sid == this.st.user.sid))
256 {
257 document.getElementById("modalNewgame").checked = false;
258 return alert("You already have a pending challenge");
259 }
260 const idxInVariants =
261 this.st.variants.findIndex(v => v.id == this.newchallenge.vid);
262 const vname = this.st.variants[idxInVariants].name;
263 const vModule = await import("@/variants/" + vname + ".js");
264 window.V = vModule.VariantRules;
265 // checkChallenge side-effect = set FEN, and mainTime + increment in seconds
266 const error = checkChallenge(this.newchallenge);
267 if (!!error)
268 return alert(error);
269 // Less than 3 days ==> live game (TODO: heuristic... 40 moves also)
270 const liveGame =
271 this.newchallenge.mainTime + 40 * this.newchallenge.increment < 3*24*60*60;
272 // Check that the players (if any indicated) are online
273 let chall =
274 {
275 id: 0, //unknown yet (no ID for live challenges)
276 from: this.st.user,
277 added: Date.now(),
278 fen: this.newchallenge.fen,
279 variant: {id: this.newchallenge.vid, name: vname},
280 nbPlayers: this.newchallenge.nbPlayers,
281 to: [
282 {id: 0, name: this.newchallenge.to[0], sid: ""},
283 {id: 0, name: this.newchallenge.to[1], sid: ""},
284 {id: 0, name: this.newchallenge.to[2], sid: ""},
285 ],
286 timeControl: this.newchallenge.timeControl,
287 mainTime: this.newchallenge.mainTime,
288 increment: this.newchallenge.increment,
289 };
290 for (let p of chall.to)
291 {
292 if (p.name != "")
293 {
294 const pIdx = this.players.findIndex(pl => pl.name == p.name);
295 // NOTE: id (server DB) and sid (socket ID).
296 // Anonymous players just have a socket ID.
297 // NOTE: for correspondance play we don't require players to be online
298 // (==> we don't have IDs, and no sid)
299 if (liveGame && pIdx === -1)
300 return alert(p.name + " is not connected");
301 p.id = this.players[pIdx].id;
302 p.sid = this.players[pIdx].sid;
303 }
304 }
305 const finishAddChallenge = () => {
306 this.challenges.push(chall);
307 // Send challenge to peers
308 const challSock =
309 {
310 code: "newchallenge",
311 chall: chall,
312 };
313 if (chall.to[0].id > 0)
314 {
315 // Challenge with targeted players
316 chall.to.forEach(p => {
317 if (p.id > 0)
318 {
319 this.st.conn.send(JSON.stringify(Object.assign(
320 {},
321 challSock,
322 {receiver: p.sid}
323 )));
324 }
325 });
326 }
327 else
328 {
329 // Open challenge: send to all connected players (except us)
330 const strChallSock = JSON.stringify(challSock);
331 this.players.forEach(p => {
332 if (p.sid != this.st.user.sid) //only sid is always set
333 this.st.conn.send(strChallSock);
334 });
335 }
336 document.getElementById("modalNewgame").checked = false;
337 };
338 if (liveGame)
339 {
340 // Live challenges have cid = 0
341 finishAddChallenge();
342 }
343 else
344 {
345 // Correspondance game: send challenge to server
346 ajax(
347 "/challenges/" + this.newchallenge.vid,
348 "POST",
349 chall,
350 response => {
351 chall.id = response.cid;
352 finishAddChallenge();
353 }
354 );
355 }
356 },
357 possibleNbplayers: function(nbp) {
358 if (this.newchallenge.vid == 0)
359 return false;
360 const variants = this.st.variants;
361 const idxInVariants =
362 variants.findIndex(v => v.id == this.newchallenge.vid);
363 return NbPlayers[variants[idxInVariants].name].includes(nbp);
364 },
365 },
366};
367</script>
368
369<style lang="sass">
370// TODO
371</style>