Simplify 'to' in newchallenge on hall view
[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";
5b020e73
BA
66import GameList from "@/components/GameList.vue";
67import ChallengeList from "@/components/ChallengeList.vue";
625022fd 68export default {
cf2343ce 69 name: "my-hall",
5b020e73
BA
70 components: {
71 GameList,
72 ChallengeList,
73 },
fb54f098
BA
74 data: function () {
75 return {
5b020e73 76 st: store.state,
b4d619d1 77 cpdisplay: "challenges",
fb54f098
BA
78 gdisplay: "live",
79 liveGames: [],
80 corrGames: [],
b4d619d1 81 challenges: [],
fb54f098 82 players: [], //online players
9d58ef95 83 newchallenge: {
fb54f098
BA
84 fen: "",
85 vid: 0,
86 nbPlayers: 0,
6faa92f2
BA
87 to: ["", "", ""], //name of challenged players
88 timeControl: "", //"2m+2s" ...etc
fb54f098
BA
89 },
90 };
91 },
b4d619d1
BA
92 computed: {
93 uniquePlayers: function() {
94 // Show e.g. "5 @nonymous", and do nothing on click on anonymous
95 let playerList = [{id:0, name:"@nonymous", count:0}];
96 this.players.forEach(p => {
97 if (p.id > 0)
98 playerList.push(p);
99 else
100 playerList[0].count++;
101 });
102 return playerList;
103 },
104 },
105 // TODO: this looks ugly... (use VueX ?!)
85e5b5c1
BA
106 watch: {
107 "st.conn": function() {
9d58ef95
BA
108 this.st.conn.onmessage = this.socketMessageListener;
109 this.st.conn.onclose = this.socketCloseListener;
85e5b5c1
BA
110 },
111 },
9d58ef95
BA
112 created: function() {
113 // TODO: ask server for current corr games (all but mines: names, ID, time control)
b4d619d1
BA
114 // also ask for corr challenges
115 // TODO: add myself to players
116 // --> when sending something, send to all players but NOT me !
9d58ef95
BA
117 if (!!this.st.conn)
118 {
119 this.st.conn.onmessage = this.socketMessageListener;
120 this.st.conn.onclose = this.socketCloseListener;
121 }
b4d619d1 122 this.players.push(this.st.user);
9d58ef95 123 },
fb54f098 124 methods: {
9d58ef95
BA
125 socketMessageListener: function(msg) {
126 const data = JSON.parse(msg.data);
127 switch (data.code)
128 {
b4d619d1
BA
129// * - receive "new game": if live, store locally + redirect to game
130// * If corr: notify "new game has started", give link, but do not redirect
9d58ef95
BA
131 case "newgame":
132 // TODO: new game just started: data contain all informations
133 // (id, players, time control, fenStart ...)
b4d619d1
BA
134 // + cid to remove challenge from list
135 break;
136// * - receive "playergame": a live game by some connected player (NO corr)
137 case "playergame":
138 // TODO: receive live game summary (update, count moves)
139 // (just players names, time control, and ID + player ID)
140 break;
141// * - receive "playerchallenges": list of challenges (sent) by some online player (NO corr)
142 case "playerchallenges":
143 // TODO: receive challenge + challenge updates
9d58ef95 144 break;
b4d619d1
BA
145 case "newmove": //live or corr
146 // TODO: name conflict ? (game "newmove" event)
147 break;
148// * - receive new challenge: if targeted, replace our name with sender name
149 case "newchallenge":
150 // receive live or corr challenge
151 break;
152// * - receive "accept/withdraw/cancel challenge": apply action to challenges list
9d58ef95
BA
153 case "acceptchallenge":
154 if (true) //TODO: if challenge is full
155 this.newGame(data.challenge, data.user); //user.id et user.name
156 break;
157 case "withdrawchallenge":
158 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
159 let chall = this.challenges[cIdx]
160 ArrayFun.remove(chall.players, p => p.id == data.uid);
161 chall.players.push({id:0, name:""});
162 break;
163 case "cancelchallenge":
164 ArrayFun.remove(this.challenges, c => c.id == data.cid);
165 break;
b4d619d1
BA
166// NOTE: finally only one connect / disconnect couple of events
167// (because on server side we wouldn't know which to choose)
168 case "connect":
169// * - receive "player connect": send all our current challenges (to him or global)
170// * Also send all our games (live - max 1 - and corr) [in web worker ?]
171// * + all our sent challenges.
9d58ef95 172 this.players.push({name:data.name, id:data.uid});
b4d619d1
BA
173 // TODO: si on est en train de jouer une partie, le notifier au nouveau connecté
174 // envoyer aussi nos défis
9d58ef95 175 break;
b4d619d1
BA
176// * - receive "player disconnect": remove from players list
177 case "disconnect":
9d58ef95 178 ArrayFun.remove(this.players, p => p.id == data.uid);
03608482
BA
179 // TODO: also remove all challenges sent by this player,
180 // and all live games where he plays and no other opponent is online
9d58ef95
BA
181 break;
182 }
183 },
184 socketCloseListener: function() {
b4d619d1
BA
185 // connexion is reinitialized in store.js
186 this.st.conn.addEventListener('message', this.socketMessageListener);
187 this.st.conn.addEventListener('close', this.socketCloseListener);
9d58ef95 188 },
fb54f098 189 showGame: function(game) {
5b020e73
BA
190 // NOTE: if we are an observer, the game will be found in main games list
191 // (sent by connected remote players)
b4d619d1 192 // TODO: game path ? /vname/gameId seems better
5b020e73 193 this.$router.push("/" + game.id)
fb54f098 194 },
b4d619d1
BA
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");
fb54f098 204 },
b4d619d1
BA
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)
fb54f098
BA
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
fb54f098
BA
238 // si pas le mien et FEN speciale :: (charger code variante et)
239 // montrer diagramme + couleur (orienté)
240 },
b4d619d1
BA
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
9d58ef95
BA
254 newChallenge: async function() {
255 const idxInVariants =
256 this.st.variants.findIndex(v => v.id == this.newchallenge.vid);
03608482 257 const vname = this.st.variants[idxInVariants].name;
9d58ef95
BA
258 const vModule = await import("@/variants/" + vname + ".js");
259 window.V = vModule.VariantRules;
03608482 260 // checkChallenge side-effect = set FEN, and mainTime + increment in seconds
9d58ef95
BA
261 const error = checkChallenge(this.newchallenge);
262 if (!!error)
263 return alert(error);
03608482
BA
264 // Less than 3 days ==> live game (TODO: heuristic... 40 moves also)
265 const liveGame =
266 this.newchallenge.mainTime + 40 * this.newchallenge.increment < 3*24*60*60;
267 // Check that the players (if any indicated) are online
268 for (let p of this.newchallenge.to)
9d58ef95 269 {
03608482
BA
270 if (p.name != "")
271 {
272 const pIdx = this.players.findIndex(pl => pl.name == p.name);
6faa92f2
BA
273 // TODO: for correspondance play we don't require players to be online
274 // (==> we don't have IDs, and no sid)
275 // NOTE: id (server DB) and sid (socket ID).
276 // Anonymous players just have a socket ID.
03608482
BA
277 if (pIdx === -1)
278 return alert(p.name + " is not connected");
279 p.id = this.players[pIdx].id;
280 p.sid = this.players[pIdx].sid;
281 }
282 }
b4d619d1 283 // TODO: clarify challenge format (too many fields for now :/ )
03608482
BA
284 const finishAddChallenge = (cid) => {
285 const chall = Object.assign(
286 {},
9d58ef95 287 this.newchallenge,
03608482
BA
288 {
289 id: cid,
290 from: this.st.user,
291 added: Date.now(),
292 vname: vname,
fb54f098
BA
293 }
294 );
03608482 295 this.challenges.push(chall);
b4d619d1 296 // Send challenge to peers
03608482 297 const chall = JSON.stringify({
b4d619d1 298 code: "newchallenge",
03608482
BA
299 sender: {name:this.st.user.name, id:this.st.user.id, sid:this.st.user.sid},
300 });
301 if (this.newchallenge.to[0].id > 0)
9d58ef95 302 {
03608482
BA
303 // Challenge with targeted players
304 this.newchallenge.to.forEach(p => {
305 if (p.id > 0)
306 this.st.conn.send(Object.assign({}, chall, {receiver: p.sid}));
9d58ef95
BA
307 });
308 }
309 else
310 {
311 // Open challenge: send to all connected players
03608482 312 this.players.forEach(p => { this.st.conn.send(chall); });
9d58ef95 313 }
b4d619d1
BA
314 document.getElementById("modalNewgame").checked = false;
315 };
316 if (liveGame)
317 {
03608482
BA
318 // Live challenges have cid = 0
319 finishAddChallenge(0);
320 }
b4d619d1 321 else
03608482 322 {
b4d619d1 323 // Correspondance game: send challenge to server
03608482
BA
324 ajax(
325 "/challenges/" + this.newchallenge.vid,
326 "POST",
327 this.newchallenge,
328 response => { finishAddChallenge(cid); }
329 );
9d58ef95 330 }
fb54f098
BA
331 },
332 possibleNbplayers: function(nbp) {
9d58ef95 333 if (this.newchallenge.vid == 0)
fb54f098 334 return false;
85e5b5c1 335 const variants = this.st.variants;
fb54f098 336 const idxInVariants =
9d58ef95 337 variants.findIndex(v => v.id == this.newchallenge.vid);
fb54f098
BA
338 return NbPlayers[variants[idxInVariants].name].includes(nbp);
339 },
340 },
85e5b5c1 341};
ccd4a2b7 342</script>
85e5b5c1
BA
343
344<style lang="sass">
345// TODO
346</style>