Some adjustments, next: fix time control handling + finish corr play
[vchess.git] / client / src / views / Hall.vue
1 <template lang="pug">
2 main
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="timeControl") {{ st.tr["Time control"] }}
13 input#timeControl(type="text" v-model="newchallenge.timeControl"
14 placeholder="3m+2s, 1h+30s, 7d+1d ...")
15 fieldset(v-if="st.user.id > 0")
16 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
17 input#selectPlayers(type="text" v-model="newchallenge.to")
18 fieldset(v-if="st.user.id > 0")
19 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
20 input#inputFen(type="text" v-model="newchallenge.fen")
21 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
22 .row
23 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
24 button(onClick="doClick('modalNewgame')") New game
25 .row
26 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
27 .collapse
28 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
29 label(for="challengeSection" aria-hidden="true") Challenges
30 div
31 .button-group
32 button(@click="cdisplay='live'") Live Challenges
33 button(@click="cdisplay='corr'") Correspondance challenges
34 ChallengeList(v-show="cdisplay=='live'"
35 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
36 ChallengeList(v-show="cdisplay=='corr'"
37 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
38 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
39 label(for="peopleSection" aria-hidden="true") People
40 div
41 .button-group
42 button(@click="pdisplay='players'") Players
43 button(@click="pdisplay='chat'") Chat
44 #players(v-show="pdisplay=='players'")
45 h3 Online players
46 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
47 :class="{anonymous: !!p.count}"
48 )
49 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
50 #chat(v-show="pdisplay=='chat'")
51 h3 Chat (TODO)
52 input#gameSection(type="radio" aria-hidden="true" name="accordion")
53 label(for="gameSection" aria-hidden="true") Games
54 div
55 .button-group
56 button(@click="gdisplay='live'") Live games
57 button(@click="gdisplay='corr'") Correspondance games
58 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
59 @show-game="showGame")
60 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
61 @show-game="showGame")
62 </template>
63
64 <script>
65 import { store } from "@/store";
66 import { checkChallenge } from "@/data/challengeCheck";
67 import { ArrayFun } from "@/utils/array";
68 import { ajax } from "@/utils/ajax";
69 import { getRandString, shuffle } from "@/utils/alea";
70 import GameList from "@/components/GameList.vue";
71 import ChallengeList from "@/components/ChallengeList.vue";
72 import { GameStorage } from "@/utils/gameStorage";
73 import { extractTime } from "@/utils/timeControl";
74 export default {
75 name: "my-hall",
76 components: {
77 GameList,
78 ChallengeList,
79 },
80 data: function () {
81 return {
82 st: store.state,
83 cdisplay: "live", //or corr
84 pdisplay: "players", //or chat
85 gdisplay: "live",
86 games: [],
87 challenges: [],
88 people: [], //(all) online players
89 newchallenge: {
90 fen: "",
91 vid: 0,
92 to: "", //name of challenged player (if any)
93 timeControl: "", //"2m+2s" ...etc
94 },
95 };
96 },
97 computed: {
98 uniquePlayers: function() {
99 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
100 let anonymous = {id:0, name:"@nonymous", count:0};
101 let playerList = [];
102 this.people.forEach(p => {
103 if (p.id > 0)
104 playerList.push(p);
105 else
106 anonymous.count++;
107 });
108 if (anonymous.count > 0)
109 playerList.push(anonymous);
110 return playerList;
111 },
112 },
113 created: function() {
114 // Always add myself to players' list
115 this.people.push(this.st.user);
116 // Retrieve live challenge (not older than 30 minute) if any:
117 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
118 if (!!chall)
119 {
120 if ((Date.now() - chall.added)/1000 <= 30*60)
121 this.challenges.push(chall);
122 else
123 localStorage.removeItem("challenge");
124 }
125 if (this.st.user.id > 0)
126 {
127 // Ask server for current corr games (all but mines)
128 ajax(
129 "/games",
130 "GET",
131 {uid: this.st.user.id, excluded: true},
132 response => {
133 this.games = this.games.concat(response.games);
134 }
135 );
136 // Also ask for corr challenges (open + sent to me)
137 ajax(
138 "/challenges",
139 "GET",
140 {uid: this.st.user.id},
141 response => {
142 console.log(response.challenges);
143 // TODO: post-treatment on challenges ?
144 Array.prototype.push.apply(this.challenges, response.challenges);
145 }
146 );
147 }
148 // 0.1] Ask server for room composition:
149 const funcPollClients = () => {
150 this.st.conn.send(JSON.stringify({code:"pollclients"}));
151 };
152 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
153 funcPollClients();
154 else //socket not ready yet (initial loading)
155 this.st.conn.onopen = funcPollClients;
156 this.st.conn.onmessage = this.socketMessageListener;
157 const socketCloseListener = () => {
158 store.socketCloseListener(); //reinitialize connexion (in store.js)
159 this.st.conn.addEventListener('message', this.socketMessageListener);
160 this.st.conn.addEventListener('close', socketCloseListener);
161 };
162 this.st.conn.onclose = socketCloseListener;
163 },
164 methods: {
165 // Helpers:
166 filterChallenges: function(type) {
167 return this.challenges.filter(c => c.type == type);
168 },
169 filterGames: function(type) {
170 return this.games.filter(c => c.type == type);
171 },
172 classifyObject: function(o) { //challenge or game
173 // Heuristic: should work for most cases... (TODO)
174 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
175 },
176 showGame: function(g) {
177 // NOTE: we are an observer, since only games I don't play are shown here
178 // ==> Moves sent by connected remote player(s) if live game
179 let url = "/game/" + g.id;
180 if (g.type == "live")
181 {
182 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
183 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
184 url += "?rid=" + remotes[rIdx].sid;
185 }
186 this.$router.push(url);
187 },
188 getVname: function(vid) {
189 const vIdx = this.st.variants.findIndex(v => v.id == vid);
190 return this.st.variants[vIdx].name;
191 },
192 getSid: function(pname) {
193 const pIdx = this.people.findIndex(pl => pl.name == pname);
194 return (pIdx === -1 ? null : this.people[pIdx].sid);
195 },
196 getPname: function(sid) {
197 const pIdx = this.people.findIndex(pl => pl.sid == sid);
198 return (pIdx === -1 ? null : this.people[pIdx].name);
199 },
200 sendSomethingTo: function(to, code, obj, warnDisconnected) {
201 const doSend = (code, obj, sid) => {
202 this.st.conn.send(JSON.stringify(Object.assign(
203 {},
204 {code: code},
205 obj,
206 {target: sid}
207 )));
208 };
209 if (!!to)
210 {
211 // Challenge with targeted players
212 const targetSid = this.getSid(to);
213 if (!targetSid)
214 {
215 if (!!warnDisconnected)
216 alert("Warning: " + pname + " is not connected");
217 }
218 else
219 doSend(code, obj, targetSid);
220 }
221 else
222 {
223 // Open challenge: send to all connected players (except us)
224 this.people.forEach(p => {
225 if (p.sid != this.st.user.sid) //only sid is always set
226 doSend(code, obj, p.sid);
227 });
228 }
229 },
230 // Messaging center:
231 socketMessageListener: function(msg) {
232 const data = JSON.parse(msg.data);
233 switch (data.code)
234 {
235 // 0.2] Receive clients list (just socket IDs)
236 case "pollclients":
237 {
238 data.sockIds.forEach(sid => {
239 this.people.push({sid:sid, id:0, name:""});
240 // Ask identity, challenges and game(s)
241 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
242 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
243 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
244 });
245 break;
246 }
247 case "askidentity":
248 {
249 // Request for identification: reply if I'm not anonymous
250 if (this.st.user.id > 0)
251 {
252 this.st.conn.send(JSON.stringify(
253 {code:"identity", user:this.st.user, target:data.from}));
254 }
255 break;
256 }
257 case "askchallenge":
258 {
259 // Send my current live challenge (if any)
260 const cIdx = this.challenges
261 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
262 if (cIdx >= 0)
263 {
264 const c = this.challenges[cIdx];
265 const myChallenge =
266 {
267 // Minimal challenge informations: (from not required)
268 id: c.id,
269 to: c.to,
270 fen: c.fen,
271 vid: c.vid,
272 timeControl: c.timeControl
273 };
274 this.st.conn.send(JSON.stringify({code:"challenge",
275 chall:myChallenge, target:data.from}));
276 }
277 break;
278 }
279 case "askgame":
280 {
281 // Send my current live game (if any)
282 GameStorage.getCurrent((game) => {
283 if (!!game)
284 {
285 const myGame =
286 {
287 // Minimal game informations:
288 id: game.id,
289 players: game.players.map(p => p.name),
290 vname: game.vname,
291
292
293
294
295 // TODO: timeControl only in challenge - no need in game (info in mainTime + increment)
296
297
298
299
300 timeControl: game.timeControl,
301 };
302 this.st.conn.send(JSON.stringify({code:"game",
303 game:myGame, target:data.from}));
304 }
305 });
306 break;
307 }
308 case "identity":
309 {
310 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
311 this.people[pIdx].id = data.user.id;
312 this.people[pIdx].name = data.user.name;
313 break;
314 }
315 case "challenge":
316 {
317 // Receive challenge from some player (+sid)
318 let newChall = data.chall;
319 newChall.type = this.classifyObject(data.chall);
320 const pIdx = this.people.findIndex(p => p.sid == data.from);
321 newChall.from = this.people[pIdx]; //may be anonymous
322 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
323 newChall.vname = this.getVname(newChall.vid); //TODO: just send vname?
324 this.challenges.push(newChall);
325 break;
326 }
327 case "game":
328 {
329 // Receive game from some player (+sid)
330 // NOTE: it may be correspondance (if newgame while we are connected)
331 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
332 {
333 let newGame = data.game;
334 newGame.type = this.classifyObject(data.game);
335 newGame.rid = data.from;
336 newGame.score = "*";
337 this.games.push(newGame);
338 }
339 break;
340 }
341 case "newgame":
342 {
343 // New game just started: data contain all information
344 if (data.gameInfo.type == "live")
345 {
346 this.startNewGame(data.gameInfo);
347 // TODO: redirect to game
348 }
349 else
350 {
351 // TODO: notify with game link but do not redirect
352 }
353 break;
354 }
355 case "refusechallenge":
356 {
357 alert(this.getPname(data.from) + " declined your challenge");
358 ArrayFun.remove(this.challenges, c => c.id == data.cid);
359 break;
360 }
361 case "deletechallenge":
362 {
363 // NOTE: the challenge may be already removed
364 ArrayFun.remove(this.challenges, c => c.id == data.cid);
365 break;
366 }
367 case "connect":
368 {
369 this.people.push({name:"", id:0, sid:data.sid});
370 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
371 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
372 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
373 break;
374 }
375 case "disconnect":
376 {
377 ArrayFun.remove(this.people, p => p.sid == data.sid);
378 // Also remove all challenges sent by this player:
379 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
380 // And all live games where he plays and no other opponent is online
381 ArrayFun.remove(this.games, g =>
382 g.type == "live" && (g.players.every(p => p.sid == data.sid
383 || !this.people.some(pl => pl.sid == p.sid))), "all");
384 break;
385 }
386 }
387 },
388 // Challenge lifecycle:
389 tryChallenge: function(player) {
390 if (player.id == 0)
391 return; //anonymous players cannot be challenged
392 this.newchallenge.to[0] = player.name;
393 doClick("modalNewgame");
394 },
395 newChallenge: async function() {
396 const vname = this.getVname(this.newchallenge.vid);
397 const vModule = await import("@/variants/" + vname + ".js");
398 window.V = vModule.VariantRules;
399 const error = checkChallenge(this.newchallenge);
400 if (!!error)
401 return alert(error);
402 const ctype = this.classifyObject(this.newchallenge);
403 // NOTE: "from" information is not required here
404 let chall =
405 {
406 fen: this.newchallenge.fen,
407 to: this.newchallenge.to,
408 timeControl: this.newchallenge.timeControl,
409 vid: this.newchallenge.vid,
410 };
411 const finishAddChallenge = (cid,warnDisconnected) => {
412 chall.id = cid || "c" + getRandString();
413 // Send challenge to peers (if connected)
414 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
415 chall.added = Date.now();
416 chall.type = ctype;
417 chall.vname = vname;
418 chall.from = this.st.user;
419 this.challenges.push(chall);
420 localStorage.setItem("challenge", JSON.stringify(chall));
421 document.getElementById("modalNewgame").checked = false;
422 };
423 const cIdx = this.challenges.findIndex(
424 c => c.from.sid == this.st.user.sid && c.type == ctype);
425 if (cIdx >= 0)
426 {
427 // Delete current challenge (will be replaced now)
428 this.sendSomethingTo(this.challenges[cIdx].to,
429 "deletechallenge", {cid:this.challenges[cIdx].id});
430 if (ctype == "corr")
431 {
432 ajax(
433 "/challenges",
434 "DELETE",
435 {id: this.challenges[cIdx].id}
436 );
437 }
438 this.challenges.splice(cIdx, 1);
439 }
440 if (ctype == "live")
441 {
442 // Live challenges have a random ID
443 finishAddChallenge(null, "warnDisconnected");
444 }
445 else
446 {
447 // Correspondance game: send challenge to server
448 ajax(
449 "/challenges",
450 "POST",
451 chall,
452 response => { finishAddChallenge(response.cid); }
453 );
454 }
455 },
456 clickChallenge: function(c) {
457 const myChallenge = (c.from.sid == this.st.user.sid //live
458 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
459 if (!myChallenge)
460 {
461 c.accepted = true;
462 if (!!c.to) //c.to == this.st.user.name (connected)
463 {
464 // TODO: if special FEN, show diagram after loading variant
465 c.accepted = confirm("Accept challenge?");
466 }
467 if (c.accepted)
468 {
469 c.seat = this.st.user;
470 this.launchGame(c);
471 }
472 else
473 {
474 this.st.conn.send(JSON.stringify({
475 code: "refusechallenge",
476 cid: c.id, target: c.from.sid}));
477 }
478 }
479 else
480 localStorage.removeItem("challenge");
481 // In all cases, the challenge is consumed:
482 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
483 // NOTE: deletechallenge event might be redundant (but it's easier this way)
484 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
485 if (c.type == "corr")
486 {
487 ajax(
488 "/challenges",
489 "DELETE",
490 {id: this.challenges[cIdx].id}
491 );
492 }
493 },
494 // NOTE: when launching game, the challenge is already deleted
495 launchGame: async function(c) {
496 const vname = this.getVname(c.vid);
497 const vModule = await import("@/variants/" + vname + ".js");
498 window.V = vModule.VariantRules;
499 // These game informations will be sent to other players
500 const gameInfo =
501 {
502 gameId: getRandString(),
503 fen: c.fen || V.GenRandInitFen(),
504 players: shuffle([c.from, c.seat]), //white then black
505 vid: c.vid,
506 timeControl: c.timeControl,
507 type: c.type,
508 };
509 this.st.conn.send(JSON.stringify({code:"newgame",
510 gameInfo:gameInfo, target:c.seat.sid}));
511 if (c.type == "live")
512 this.startNewGame(gameInfo);
513 else //corr: game only on server
514 {
515 ajax(
516 "/games",
517 "POST",
518 {gameInfo: gameInfo}
519 );
520 }
521 },
522 // NOTE: for live games only (corr games are launched on server)
523 startNewGame: function(gameInfo) {
524 // Extract times (in [milli]seconds), set clocks
525 const tc = extractTime(gameInfo.timeControl);
526 let initime = [...Array(gameInfo.players.length)];
527 initime[0] = Date.now();
528 const game =
529 {
530 // Game infos: constant
531 gameId: gameInfo.gameId,
532 vname: this.getVname(gameInfo.vid),
533 fenStart: gameInfo.fen,
534 players: gameInfo.players,
535 mainTime: tc.mainTime,
536 increment: tc.increment,
537 mode: "live", //function for live games only
538 // Game state: will be updated
539 fen: gameInfo.fen,
540 moves: [],
541 clocks: [...Array(gameInfo.players.length)].fill(tc.mainTime),
542 initime: initime,
543 score: "*",
544 };
545 GameStorage.add(game);
546 if (this.st.settings.sound >= 1)
547 new Audio("/sounds/newgame.mp3").play().catch(err => {});
548 // TODO: redirect to game
549 },
550 },
551 };
552 </script>
553
554 <style lang="sass">
555 // TODO
556 </style>