Save state
[vchess.git] / client / src / views / Hall.vue
... / ...
CommitLineData
1<template lang="pug">
2main
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"] }}
9 select#selectVariant(v-model="newchallenge.vid")
10 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
11 fieldset
12 label(for="selectNbPlayers") {{ st.tr["Number of players"] }}
13 select#selectNbPlayers(v-model="newchallenge.nbPlayers")
14 option(v-show="possibleNbplayers(2)" value="2" selected) 2
15 option(v-show="possibleNbplayers(3)" value="3") 3
16 option(v-show="possibleNbplayers(4)" value="4") 4
17 fieldset
18 label(for="timeControl") {{ st.tr["Time control"] }}
19 input#timeControl(type="text" v-model="newchallenge.timeControl"
20 placeholder="3m+2s, 1h+30s, 7d+1d ...")
21 fieldset(v-if="st.user.id > 0")
22 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
23 #selectPlayers
24 input(type="text" v-model="newchallenge.to[0]")
25 input(v-show="newchallenge.nbPlayers>=3" type="text"
26 v-model="newchallenge.to[1]")
27 input(v-show="newchallenge.nbPlayers==4" type="text"
28 v-model="newchallenge.to[2]")
29 fieldset(v-if="st.user.id > 0")
30 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
31 input#inputFen(type="text" v-model="newchallenge.fen")
32 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
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
37 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
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")
49 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
50 label(for="peopleSection" aria-hidden="true") People
51 div
52 .button-group
53 button(@click="pdisplay='players'") Players
54 button(@click="pdisplay='chat'") Chat
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)
63 input#gameSection(type="radio" aria-hidden="true" name="accordion")
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")
73</template>
74
75<script>
76import { store } from "@/store";
77import { NbPlayers } from "@/data/nbPlayers";
78import { checkChallenge } from "@/data/challengeCheck";
79import { ArrayFun } from "@/utils/array";
80import { ajax } from "@/utils/ajax";
81import { getRandString, shuffle } from "@/utils/alea";
82import { extractTime } from "@/utils/timeControl";
83import GameList from "@/components/GameList.vue";
84import ChallengeList from "@/components/ChallengeList.vue";
85export default {
86 name: "my-hall",
87 components: {
88 GameList,
89 ChallengeList,
90 },
91 data: function () {
92 return {
93 st: store.state,
94 cdisplay: "live", //or corr
95 pdisplay: "players", //or chat
96 gdisplay: "live",
97 games: [],
98 challenges: [],
99 players: [], //online players (rename into "people" ?)
100 newchallenge: {
101 fen: "",
102 vid: 0,
103 nbPlayers: 0,
104 to: ["", "", ""], //name of challenged players
105 timeControl: "", //"2m+2s" ...etc
106 },
107 };
108 },
109 computed: {
110 uniquePlayers: function() {
111 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
112 let anonymous = {id:0, name:"@nonymous", count:0};
113 let playerList = [];
114 this.players.forEach(p => {
115 if (p.id > 0)
116 playerList.push(p);
117 else
118 anonymous.count++;
119 });
120 if (anonymous.count > 0)
121 playerList.push(anonymous);
122 return playerList;
123 },
124 },
125 created: function() {
126 // Always add myself to players' list
127 this.players.push(this.st.user);
128 // Ask server for current corr games (all but mines)
129// ajax(
130// "",
131// "GET",
132// response => {
133//
134// }
135// );
136// // Also ask for corr challenges (all)
137// ajax(
138// "",
139// "GET",
140// response => {
141//
142// }
143// );
144 // 0.1] Ask server for for room composition:
145 const socketOpenListener = () => {
146 this.st.conn.send(JSON.stringify({code:"pollclients"}));
147 };
148 this.st.conn.onopen = socketOpenListener;
149 // TODO: is this required here?
150 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
151 this.st.conn.onmessage = this.socketMessageListener;
152 const oldOnclose = this.st.conn.onclose;
153 const socketCloseListener = () => {
154 oldOnclose(); //reinitialize connexion (in store.js)
155 this.st.conn.addEventListener('message', this.socketMessageListener);
156 this.st.conn.addEventListener('close', socketCloseListener);
157 };
158 this.st.conn.onclose = socketCloseListener;
159 },
160 methods: {
161 // Helpers:
162 filterChallenges: function(type) {
163 return this.challenges.filter(c => c.type == type);
164 },
165 filterGames: function(type) {
166 return this.games.filter(c => c.type == type);
167 },
168 classifyChallenge: function(c) {
169 // Heuristic: should work for most cases... (TODO)
170 return (c.timeControl.indexOf('d') === -1 ? "live" : "corr");
171 },
172 possibleNbplayers: function(nbp) {
173 if (this.newchallenge.vid == 0)
174 return false;
175 const idxInVariants =
176 this.st.variants.findIndex(v => v.id == this.newchallenge.vid);
177 return NbPlayers[this.st.variants[idxInVariants].name].includes(nbp);
178 },
179 showGame: function(game) {
180 // NOTE: we are an observer, since only games I don't play are shown here
181 // ==> Moves sent by connected remote player(s)
182 const sids = game.players.map(p => p.sid).join(",");
183 this.$router.push("/" + game.id + "?sids=" + sids);
184 },
185 getVname: function(vid) {
186 const vIdx = this.st.variants.findIndex(v => v.id == vid);
187 return this.st.variants[vIdx].name;
188 },
189 getSid: function(pname) {
190 const pIdx = this.players.findIndex(pl => pl.name == pname);
191 return (pIdx === -1 ? null : this.players[pIdx].sid);
192 },
193 getPname: function(sid) {
194 const pIdx = this.players.findIndex(pl => pl.sid == sid);
195 return (pIdx === -1 ? null : this.players[pIdx].name);
196 },
197 sendSomethingTo: function(to, code, obj, warnDisconnected) {
198 const doSend = (code, obj, sid) => {
199 this.st.conn.send(JSON.stringify(Object.assign(
200 {},
201 {code: code},
202 obj,
203 {target: sid}
204 )));
205 };
206 else if (!!to[0])
207 {
208 to.forEach(pname => {
209 // Challenge with targeted players
210 const targetSid = this.getSid(pname);
211 if (!targetSid)
212 {
213 if (!!warnDisconnected)
214 alert("Warning: " + pname + " is not connected");
215 }
216 else
217 doSend(code, obj, targetSid);
218 });
219 }
220 else
221 {
222 // Open challenge: send to all connected players (except us)
223 this.players.forEach(p => {
224 if (p.sid != this.st.user.sid) //only sid is always set
225 doSend(code, obj, p.sid);
226 });
227 }
228 },
229 // Messaging center:
230 socketMessageListener: function(msg) {
231 // Save and call current st.conn.onmessage if one was already defined
232 // --> also needed in future Game.vue (also in Chat.vue component)
233 this.oldOnmessage(msg);
234 const data = JSON.parse(msg.data);
235 switch (data.code)
236 {
237 // 0.2] Receive clients list (just socket IDs)
238 case "pollclients":
239 {
240 data.sockIds.forEach(sid => {
241 this.players.push({sid:sid, id:0, name:""});
242 // Ask identity, challenges and game(s)
243 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
244 this.st.conn.send(JSON.stringify({code:"askchallenges", target:sid}));
245 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
246 });
247 break;
248 }
249 case "askidentity":
250 {
251 // Request for identification: reply if I'm not anonymous
252 if (this.st.user.id > 0)
253 {
254 this.st.conn.send(JSON.stringify(
255 {code:"identity", user:this.st.user, target:data.from}));
256 }
257 break;
258 }
259 case "askchallenge":
260 {
261 // Send my current live challenge (if any)
262 const cIdx = this.challenges
263 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
264 if (cIdx >= 0)
265 {
266 const c = this.challenges[cIdx];
267 const myChallenge =
268 {
269 // Minimal challenge informations: (from not required)
270 to: c.to,
271 fen: c.fen,
272 vid: c.vid,
273 timeControl: c.timeControl
274 };
275 this.st.conn.send(JSON.stringify({code:"challenge",
276 challenge:myChallenge, target:data.from}));
277 }
278 break;
279 }
280 case "askgame":
281 {
282 // TODO: Send my current live game (if any): variant, players, movesCount
283 break;
284 }
285 case "identity":
286 {
287 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
288 this.players[pIdx].id = data.user.id;
289 this.players[pIdx].name = data.user.name;
290 break;
291 }
292 case "challenge":
293 {
294 // Receive challenge from some player (+sid)
295 let newChall = data.chall;
296 newChall.type = this.classifyChallenge(data.chall);
297 const pIdx = this.players.findIndex(p => p.sid == data.from);
298 newChall.from = this.players[pIdx]; //may be anonymous
299 newChall.added = Date.now();
300 newChall.vname = this.getVname(newChall.vid);
301 this.challenges.push(newChall);
302 break;
303 }
304 case "game":
305 {
306 // Receive game from some player (+sid)
307 // TODO: receive game summary (update, count moves)
308 // (just players names, time control, and ID + player ID)
309 // NOTE: it may be correspondance (if newgame while we are connected)
310 break;
311 }
312// * - receive "new game": if live, store locally + redirect to game
313// * If corr: notify "new game has started", give link, but do not redirect
314 case "newgame":
315 {
316 // Delete corresponding challenge:
317 ArrayFun.remove(this.challenges, c => c.id == data.cid);
318 // New game just started: data contain all informations
319 this.newGame(data.gameInfo);
320 break;
321 }
322// * - receive "accept/withdraw/cancel challenge": apply action to challenges list
323 // NOTE: challenge "socket" actions accept+withdraw only for live challenges
324 case "acceptchallenge":
325 {
326 // Someone accept an open (or targeted) challenge
327 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
328 let c = this.challenges[cIdx];
329 if (!c.seats)
330 c.seats = [...Array(c.to.length)];
331 const pIdx = this.players.findIndex(p => p.sid == data.from);
332 // Put this player in the first empty seat we find:
333 let sIdx = 0;
334 for (; sIdx<c.seats.length; sIdx++)
335 {
336 if (!c.seats[sIdx])
337 {
338 c.seats[sIdx] = this.players[pIdx];
339 break;
340 }
341 }
342 if (sIdx == c.seats.length - 1)
343 {
344 // All seats are taken: game can start
345 this.launchGame(c);
346 }
347 break;
348 }
349 case "withdrawchallenge":
350 {
351 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
352 let seats = this.challenges[cIdx].seats;
353 const sIdx = seats.findIndex(s => s.sid == data.sid);
354 seats[sIdx] = undefined;
355 break;
356 }
357 case "refusechallenge":
358 {
359 alert(this.getPname(data.from) + " refused your challenge");
360 ArrayFun.remove(this.challenges, c => c.id == data.cid);
361 break;
362 }
363 case "deletechallenge":
364 {
365 ArrayFun.remove(this.challenges, c => c.id == data.cid);
366 break;
367 }
368 case "connect":
369 {
370 this.players.push({name:"", id:0, sid:data.sid});
371 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
372 break;
373// * - receive "player connect": TODO = send our current challenge (to him or global)
374// * Also send all our games (live - max 1 - and corr) [in web worker ?]
375 }
376// * - receive "player disconnect": remove from players list
377 case "disconnect":
378 {
379 ArrayFun.remove(this.players, p => p.sid == data.sid);
380 // Also remove all challenges sent by this player:
381 for (let cIdx = this.challenges.length-1; cIdx >= 0; cIdx--)
382 {
383 if (this.challenges[cIdx].from.sid == data.sid)
384 this.challenges.splice(cIdx, 1);
385 }
386 // and all live games where he plays and no other opponent is online
387 // TODO
388 break;
389 }
390 }
391 },
392 // Challenge lifecycle:
393 tryChallenge: function(player) {
394 if (player.id == 0)
395 return; //anonymous players cannot be challenged
396 this.newchallenge.to[0] = player.name;
397 doClick("modalNewgame");
398 },
399 newChallenge: async function() {
400 const vname = this.getVname(this.newchallenge.vid);
401 const vModule = await import("@/variants/" + vname + ".js");
402 window.V = vModule.VariantRules;
403 const error = checkChallenge(this.newchallenge);
404 if (!!error)
405 return alert(error);
406 const ctype = this.classifyChallenge(this.newchallenge);
407 const cto = this.newchallenge.to.slice(0, this.newchallenge.nbPlayers);
408 // NOTE: "from" information is not required here
409 let chall =
410 {
411 fen: this.newchallenge.fen,
412 to: cto,
413 timeControl: this.newchallenge.timeControl,
414 vid: this.newchallenge.vid,
415 };
416 const finishAddChallenge = (cid) => {
417 chall.id = cid || "c" + getRandString();
418 // Send challenge to peers
419 this.sendSomethingTo(cto, "challenge", {chall:chall}, "warnDisconnected");
420 chall.added = Date.now();
421 chall.type = ctype;
422 chall.vname = vname;
423 chall.from = this.st.user;
424 this.challenges.push(chall);
425 document.getElementById("modalNewgame").checked = false;
426 };
427 const cIdx = this.challenges.findIndex(
428 c => c.from.sid == this.st.user.sid && c.type == ctype);
429 if (cIdx >= 0)
430 {
431 // Delete current challenge (will be replaced now)
432 this.sendSomethingTo(this.challenges[cIdx].to,
433 "deletechallenge", {cid:this.challenges[cIdx].id});
434 if (ctype == "corr")
435 {
436 ajax(
437 "/challenges",
438 "DELETE",
439 {id: this.challenges[cIdx].id}
440 );
441 }
442 this.challenges.splice(cIdx, 1);
443 }
444 if (ctype == "live")
445 {
446 // Live challenges have a random ID
447 finishAddChallenge();
448 }
449 else
450 {
451 // Correspondance game: send challenge to server
452 ajax(
453 "/challenges",
454 "POST",
455 chall,
456 response => { finishAddChallenge(response.cid); }
457 );
458 }
459 },
460// * - accept challenge (corr or live) --> send info to challenge creator
461// * - cancel challenge (click on sent challenge) --> send info to all concerned players
462// * - withdraw from challenge (if >= 3 players and previously accepted)
463// * --> send info to challenge creator
464// * - refuse challenge: send "refuse" to challenge sender, and "delete" to others
465// * - prepare and start new game (if challenge is full after acceptation)
466// * --> include challenge ID (so that opponents can delete the challenge too)
467 clickChallenge: function(c) {
468 // TODO: also correspondance case (send to server)
469 if (!!c.accepted)
470 {
471 // It's a multiplayer challenge I accepted: withdraw
472 this.st.conn.send(JSON.stringify({code: "withdrawchallenge",
473 cid: c.id, target: c.from.sid}));
474 c.accepted = false;
475 }
476 else if (c.from.sid == this.st.user.sid) //it's my challenge: cancel it
477 {
478 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
479 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
480 }
481 else //accept (or refuse) a challenge
482 {
483 c.accepted = true;
484 if (!!c.to[0])
485 {
486 // TODO: if special FEN, show diagram after loading variant
487 c.accepted = confirm("Accept challenge?");
488 }
489 this.st.conn.send(JSON.stringify({
490 code: (c.accepted ? "accept" : "refuse") + "challenge",
491 cid: c.id, target: c.from.sid}));
492 if (!c.accepted)
493 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
494 }
495 },
496 // c.type == corr alors use id...sinon sid (figés)
497 // NOTE: only for live games ?
498 launchGame: function(c) {
499 // Just assign colors and pass the message
500 const vname = this.getVname(c.vid);
501 const vModule = await import("@/variants/" + vname + ".js");
502 window.V = vModule.VariantRules;
503 let players = [c.from];
504 Array.prototype.push.apply(players, c.seats);
505 let gameInfo =
506 {
507 fen: c.fen || V.GenRandInitFen(),
508 // Shuffle players order (white then black then other colors).
509 // Players' names may be required if game start when a player is offline
510 players: shuffle(players).map(p => {name:p.name, sid:p.sid},
511 vid: c.vid,
512 timeControl: c.timeControl,
513 };
514 c.seats.forEach(s => {
515 // NOTE: cid required to remove challenge
516 this.st.conn.send(JSON.stringify({code:"newgame",
517 gameInfo:gameInfo, cid:c.id, target:s.sid}));
518 });
519 // Delete corresponding challenge:
520 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
521 this.newGame(gameInfo); //also!
522 },
523 // NOTE: for live games only (corr games are laucnhed on server)
524 newGame: function(gameInfo) {
525 // Extract times (in [milli]seconds), set clocks, store in localStorage
526 const tc = extractTime(gameInfo.timeControl);
527 dddddddd
528 // TODO: [in game] send move + elapsed time (in milliseconds); in case of "lastate" message too
529 // //setStorage(game); //TODO
530// if (this.settings.sound >= 1)
531// new Audio("/sounds/newgame.mp3").play().catch(err => {});
532 },
533 },
534};
535</script>
536
537<style lang="sass">
538// TODO
539</style>