3 input#modalInfo.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="infoMessage")
5 .card.smallpad.small-modal.text-center
6 label.modal-close(for="modalInfo")
8 p(v-html="infoMessage")
9 input#modalNewgame.modal(type="checkbox")
10 div(role="dialog" data-checkbox="modalNewgame"
11 aria-labelledby="titleFenedit")
12 .card.smallpad(@keyup.enter="newChallenge")
13 label#closeNewgame.modal-close(for="modalNewgame")
15 label(for="selectVariant") {{ st.tr["Variant"] }}
16 select#selectVariant(v-model="newchallenge.vid")
17 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
19 label(for="timeControl") {{ st.tr["Time control"] }}
20 input#timeControl(type="text" v-model="newchallenge.timeControl"
21 placeholder="3m+2s, 1h+30s, 7d+1d ...")
22 fieldset(v-if="st.user.id > 0")
23 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
24 input#selectPlayers(type="text" v-model="newchallenge.to")
25 fieldset(v-if="st.user.id > 0")
26 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
27 input#inputFen(type="text" v-model="newchallenge.fen")
28 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
31 button#newGame(onClick="doClick('modalNewgame')") New game
33 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
35 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
36 label(for="challengeSection" aria-hidden="true") Challenges
39 button(@click="cdisplay='live'") Live Challenges
40 button(@click="cdisplay='corr'") Correspondance challenges
41 ChallengeList(v-show="cdisplay=='live'"
42 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
43 ChallengeList(v-show="cdisplay=='corr'"
44 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
45 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
46 label(for="peopleSection" aria-hidden="true") People
49 button(@click="pdisplay='players'") Players
50 button(@click="pdisplay='chat'") Chat
51 #players(v-show="pdisplay=='players'")
52 p.text-center(v-for="p in uniquePlayers")
53 span(:class="{anonymous: !!p.count}")
54 | {{ (p.name || '@nonymous') + (!!p.count ? " ("+p.count+")" : "") }}
55 button.player-action(v-if="!p.count" @click="challOrWatch(p,$event)")
56 | {{ whatPlayerDoes(p) }}
57 #chat(v-show="pdisplay=='chat'")
59 input#gameSection(type="radio" aria-hidden="true" name="accordion")
60 label(for="gameSection" aria-hidden="true") Games
63 button(@click="gdisplay='live'") Live games
64 button(@click="gdisplay='corr'") Correspondance games
65 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
66 @show-game="showGame")
67 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
68 @show-game="showGame")
72 import { store } from "@/store";
73 import { checkChallenge } from "@/data/challengeCheck";
74 import { ArrayFun } from "@/utils/array";
75 import { ajax } from "@/utils/ajax";
76 import { getRandString, shuffle } from "@/utils/alea";
77 import Chat from "@/components/Chat.vue";
78 import GameList from "@/components/GameList.vue";
79 import ChallengeList from "@/components/ChallengeList.vue";
80 import { GameStorage } from "@/utils/gameStorage";
91 cdisplay: "live", //or corr
92 pdisplay: "players", //or chat
96 people: {}, //people in main hall
101 to: "", //name of challenged player (if any)
102 timeControl: "", //"2m+2s" ...etc
107 // st.variants changes only once, at loading from [] to [...]
108 "st.variants": function(variantArray) {
109 // Set potential challenges and games variant names:
110 this.challenges.forEach(c => {
112 c.vname = this.getVname(c.vid);
114 this.games.forEach(g => {
116 g.vname = this.getVname(g.vid);
121 uniquePlayers: function() {
122 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
123 let anonymous = {name:"", count:0};
125 Object.values(this.people).forEach(p => {
128 // We don't count registered users connections: either they are here or not.
129 if (!playerList[p.id])
130 playerList[p.id] = {name: p.name};
135 if (anonymous.count > 0)
136 playerList[0] = anonymous;
137 return Object.values(playerList);
140 created: function() {
141 // Always add myself to players' list
142 const my = this.st.user;
143 this.$set(this.people, my.sid, {id:my.id, name:my.name});
144 // Retrieve live challenge (not older than 30 minute) if any:
145 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
148 if ((Date.now() - chall.added)/1000 <= 30*60)
149 this.challenges.push(chall);
151 localStorage.removeItem("challenge");
153 // Ask server for current corr games (all but mines)
157 {uid: this.st.user.id, excluded: true},
159 this.games = this.games.concat(response.games.map(g => {
160 const type = this.classifyObject(g);
161 const vname = this.getVname(g.vid);
162 return Object.assign({}, g, {type: type, vname: vname});
166 // Also ask for corr challenges (open + sent to me)
170 {uid: this.st.user.id},
172 // Gather all senders names, and then retrieve full identity:
173 // (TODO [perf]: some might be online...)
174 const uids = response.challenges.map(c => { return c.uid });
177 { ids: uids.join(",") },
180 response2.users.forEach(u => {names[u.id] = u.name});
181 this.challenges = this.challenges.concat(
182 response.challenges.map(c => {
183 // (just players names in fact)
184 const from = {name: names[c.uid], id: c.uid};
185 const type = this.classifyObject(c);
186 const vname = this.getVname(c.vid);
187 return Object.assign({}, c, {type: type, vname: vname, from: from});
194 // 0.1] Ask server for room composition:
195 const funcPollClients = () => {
196 this.st.conn.send(JSON.stringify({code:"pollclients"}));
198 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
200 else //socket not ready yet (initial loading)
201 this.st.conn.onopen = funcPollClients;
202 this.st.conn.onmessage = this.socketMessageListener;
203 const socketCloseListener = () => {
204 store.socketCloseListener(); //reinitialize connexion (in store.js)
205 this.st.conn.addEventListener('message', this.socketMessageListener);
206 this.st.conn.addEventListener('close', socketCloseListener);
208 this.st.conn.onclose = socketCloseListener;
212 filterChallenges: function(type) {
213 return this.challenges.filter(c => c.type == type);
215 filterGames: function(type) {
216 return this.games.filter(g => g.type == type);
218 classifyObject: function(o) { //challenge or game
219 // Heuristic: should work for most cases... (TODO)
220 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
222 showGame: function(g) {
223 // NOTE: we are an observer, since only games I don't play are shown here
224 // ==> Moves sent by connected remote player(s) if live game
225 let url = "/game/" + g.id;
226 if (g.type == "live")
227 url += "?rid=" + g.rid;
228 this.$router.push(url);
230 getVname: function(vid) {
231 const variant = this.st.variants.find(v => v.id == vid);
232 // this.st.variants might be uninitialized (variant == null)
233 return (!!variant ? variant.name : "");
235 whatPlayerDoes: function(p) {
236 if (this.games.some(g => g.players.some(pl => pl.sid == p.sid)))
238 return "Challenge"; //player is available
240 sendSomethingTo: function(to, code, obj, warnDisconnected) {
241 const doSend = (code, obj, sid) => {
242 this.st.conn.send(JSON.stringify(Object.assign(
251 // Challenge with targeted players
253 Object.keys(this.people).find(sid => this.people[sid].name == to);
256 if (!!warnDisconnected)
257 alert("Warning: " + pname + " is not connected");
260 doSend(code, obj, targetSid);
264 // Open challenge: send to all connected players (except us)
265 Object.keys(this.people).forEach(sid => {
266 if (sid != this.st.user.sid)
267 doSend(code, obj, sid);
272 socketMessageListener: function(msg) {
273 const data = JSON.parse(msg.data);
277 alert("Warning: duplicate 'offline' connection");
279 // 0.2] Receive clients list (just socket IDs)
282 data.sockIds.forEach(sid => {
283 this.$set(this.people, sid, {id:0, name:""});
284 // Ask identity, challenges and game(s)
285 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
286 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
288 // Also ask current games to all playing peers (TODO: some design issue)
289 this.st.conn.send(JSON.stringify({code:"askgames"}));
294 // Request for identification: reply if I'm not anonymous
295 if (this.st.user.id > 0)
297 this.st.conn.send(JSON.stringify({code:"identity",
299 // NOTE: decompose to avoid revealing email
300 name: this.st.user.name,
301 sid: this.st.user.sid,
310 this.$set(this.people, data.user.sid,
311 {id: data.user.id, name: data.user.name});
316 // Send my current live challenge (if any)
317 const cIdx = this.challenges
318 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
321 const c = this.challenges[cIdx];
324 // Minimal challenge informations: (from not required)
329 timeControl: c.timeControl
331 this.st.conn.send(JSON.stringify({code:"challenge",
332 chall:myChallenge, target:data.from}));
338 // Receive challenge from some player (+sid)
339 let newChall = data.chall;
340 newChall.type = this.classifyObject(data.chall);
342 Object.assign({sid:data.from}, this.people[data.from]);
343 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
344 newChall.vname = this.getVname(newChall.vid);
345 this.challenges.push(newChall);
350 // Receive game from some player (+sid)
351 // NOTE: it may be correspondance (if newgame while we are connected)
352 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
354 let newGame = data.game;
355 newGame.type = this.classifyObject(data.game);
356 newGame.vname = this.getVname(data.game.vid);
357 newGame.rid = data.from;
359 this.games.push(newGame);
365 // TODO: next line required ?!
366 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
367 // New game just started: data contain all information
368 if (this.classifyObject(data.gameInfo) == "live")
369 this.startNewGame(data.gameInfo);
372 this.infoMessage = "New game started: " +
373 "<a href='#/game/" + data.gameInfo.id + "'>" +
374 "#/game/" + data.gameInfo.id + "</a>";
375 let modalBox = document.getElementById("modalInfo");
376 modalBox.checked = true;
377 setTimeout(() => { modalBox.checked = false; }, 3000);
381 case "refusechallenge":
383 alert(this.people[data.from].name + " declined your challenge");
384 ArrayFun.remove(this.challenges, c => c.id == data.cid);
387 case "deletechallenge":
389 // NOTE: the challenge may be already removed
390 ArrayFun.remove(this.challenges, c => c.id == data.cid);
391 localStorage.removeItem("challenge"); //in case of
396 this.$set(this.people, data.from, {name:"", id:0});
397 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
398 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
399 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
404 this.$delete(this.people, data.from);
405 // Also remove all challenges sent by this player:
406 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
407 // And all live games where he plays and no other opponent is online
408 ArrayFun.remove(this.games, g =>
409 g.type == "live" && (g.players.every(p => p.sid == data.from
410 || !this.people[p.sid])), "all");
415 // Challenge lifecycle:
416 tryChallenge: function(player) {
418 return; //anonymous players cannot be challenged
419 this.newchallenge.to = player.name;
420 doClick("modalNewgame");
422 challOrWatch: function(p, e) {
423 switch (e.target.innerHTML)
426 this.tryChallenge(p);
429 // NOTE: this search for game was already done for rendering
430 this.showGame(this.games.find(
431 g => g.players.some(pl => pl.sid == p.sid)));
435 newChallenge: async function() {
436 const vname = this.getVname(this.newchallenge.vid);
437 const vModule = await import("@/variants/" + vname + ".js");
438 window.V = vModule.VariantRules;
439 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
440 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
441 const error = checkChallenge(this.newchallenge);
444 const ctype = this.classifyObject(this.newchallenge);
445 if (ctype == "corr" && this.st.user.id <= 0)
446 return alert("Please log in to play correspondance games");
447 // NOTE: "from" information is not required here
448 let chall = Object.assign({}, this.newchallenge);
449 const finishAddChallenge = (cid,warnDisconnected) => {
450 chall.id = cid || "c" + getRandString();
451 // Send challenge to peers (if connected)
452 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
453 chall.added = Date.now();
454 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
457 chall.from = { //decompose to avoid revealing email
458 sid: this.st.user.sid,
460 name: this.st.user.name,
462 this.challenges.push(chall);
464 localStorage.setItem("challenge", JSON.stringify(chall));
465 document.getElementById("modalNewgame").checked = false;
467 const cIdx = this.challenges.findIndex(
468 c => c.from.sid == this.st.user.sid && c.type == ctype);
471 // Delete current challenge (will be replaced now)
472 this.sendSomethingTo(this.challenges[cIdx].to,
473 "deletechallenge", {cid:this.challenges[cIdx].id});
479 {id: this.challenges[cIdx].id}
482 this.challenges.splice(cIdx, 1);
486 // Live challenges have a random ID
487 finishAddChallenge(null, "warnDisconnected");
491 // Correspondance game: send challenge to server
496 response => { finishAddChallenge(response.cid); }
500 clickChallenge: function(c) {
501 const myChallenge = (c.from.sid == this.st.user.sid //live
502 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
505 if (c.type == "corr" && this.st.user.id <= 0)
506 return alert("Please log in to accept corr challenges");
508 if (!!c.to) //c.to == this.st.user.name (connected)
510 // TODO: if special FEN, show diagram after loading variant
511 c.accepted = confirm("Accept challenge?");
515 c.seat = { //again, avoid c.seat = st.user to not reveal email
516 sid: this.st.user.sid,
518 name: this.st.user.name,
524 this.st.conn.send(JSON.stringify({
525 code: "refusechallenge",
526 cid: c.id, target: c.from.sid}));
531 if (c.type == "corr")
540 localStorage.removeItem("challenge");
542 // In (almost) all cases, the challenge is consumed:
543 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
544 // NOTE: deletechallenge event might be redundant (but it's easier this way)
545 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
547 // NOTE: when launching game, the challenge is already deleted
548 launchGame: async function(c) {
549 const vModule = await import("@/variants/" + c.vname + ".js");
550 window.V = vModule.VariantRules;
551 // These game informations will be sent to other players
555 fen: c.fen || V.GenRandInitFen(),
556 players: shuffle([c.from, c.seat]), //white then black
558 vname: c.vname, //theoretically vid is enough, but much easier with vname
559 timeControl: c.timeControl,
561 let target = c.from.sid; //may not be defined if corr + offline opp
564 target = Object.keys(this.people).find(sid =>
565 this.people[sid].id == c.from.id);
567 const tryNotifyOpponent = () => {
568 if (!!target) //opponent is online
570 this.st.conn.send(JSON.stringify({code:"newgame",
571 gameInfo:gameInfo, target:target, cid:c.id}));
574 if (c.type == "live")
577 this.startNewGame(gameInfo);
579 else //corr: game only on server
584 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
586 gameInfo.id = response.gameId;
588 this.$router.push("/game/" + response.gameId);
592 // Send game info to everyone except opponent (and me)
593 this.st.conn.send(JSON.stringify({code:"game",
594 game: { //minimal game info:
596 players: gameInfo.players.map(p => p.name),
598 timeControl: gameInfo.timeControl,
602 // NOTE: for live games only (corr games start on the server)
603 startNewGame: function(gameInfo) {
604 const game = Object.assign({}, gameInfo, {
605 // (other) Game infos: constant
606 fenStart: gameInfo.fen,
608 // Game state (including FEN): will be updated
610 clocks: [-1, -1], //-1 = unstarted
611 initime: [0, 0], //initialized later
614 GameStorage.add(game);
615 if (this.st.settings.sound >= 1)
616 new Audio("/sounds/newgame.mp3").play().catch(err => {});
617 this.$router.push("/game/" + gameInfo.id);
626 margin: 10px auto 5px auto