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(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 && p.name != st.user.name"
56 @click="challOrWatch(p,$event)")
57 | {{ whatPlayerDoes(p) }}
58 #chat(v-show="pdisplay=='chat'")
60 input#gameSection(type="radio" aria-hidden="true" name="accordion")
61 label(for="gameSection" aria-hidden="true") Games
64 button(@click="gdisplay='live'") Live games
65 button(@click="gdisplay='corr'") Correspondance games
66 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
67 @show-game="showGame")
68 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
69 @show-game="showGame")
73 import { store } from "@/store";
74 import { checkChallenge } from "@/data/challengeCheck";
75 import { ArrayFun } from "@/utils/array";
76 import { ajax } from "@/utils/ajax";
77 import { getRandString, shuffle } from "@/utils/alea";
78 import Chat from "@/components/Chat.vue";
79 import GameList from "@/components/GameList.vue";
80 import ChallengeList from "@/components/ChallengeList.vue";
81 import { GameStorage } from "@/utils/gameStorage";
92 cdisplay: "live", //or corr
93 pdisplay: "players", //or chat
97 people: {}, //people in main hall
102 to: "", //name of challenged player (if any)
103 timeControl: "", //"2m+2s" ...etc
108 // st.variants changes only once, at loading from [] to [...]
109 "st.variants": function(variantArray) {
110 // Set potential challenges and games variant names:
111 this.challenges.forEach(c => {
113 c.vname = this.getVname(c.vid);
115 this.games.forEach(g => {
117 g.vname = this.getVname(g.vid);
122 uniquePlayers: function() {
123 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
124 let anonymous = {name:"", count:0};
126 Object.values(this.people).forEach(p => {
129 // We don't count registered users connections: either they are here or not.
130 if (!playerList[p.id])
131 playerList[p.id] = {name: p.name};
136 if (anonymous.count > 0)
137 playerList[0] = anonymous;
138 return Object.values(playerList);
141 created: function() {
142 // Always add myself to players' list
143 const my = this.st.user;
144 this.$set(this.people, my.sid, {id:my.id, name:my.name});
145 // Retrieve live challenge (not older than 30 minute) if any:
146 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
149 if ((Date.now() - chall.added)/1000 <= 30*60)
150 this.challenges.push(chall);
152 localStorage.removeItem("challenge");
154 // Ask server for current corr games (all but mines)
158 {uid: this.st.user.id, excluded: true},
160 this.games = this.games.concat(response.games.map(g => {
161 const type = this.classifyObject(g);
162 const vname = this.getVname(g.vid);
163 return Object.assign({}, g, {type: type, vname: vname});
167 // Also ask for corr challenges (open + sent to me)
171 {uid: this.st.user.id},
173 // Gather all senders names, and then retrieve full identity:
174 // (TODO [perf]: some might be online...)
175 const uids = response.challenges.map(c => { return c.uid });
178 { ids: uids.join(",") },
181 response2.users.forEach(u => {names[u.id] = u.name});
182 this.challenges = this.challenges.concat(
183 response.challenges.map(c => {
184 // (just players names in fact)
185 const from = {name: names[c.uid], id: c.uid};
186 const type = this.classifyObject(c);
187 const vname = this.getVname(c.vid);
188 return Object.assign({}, c, {type: type, vname: vname, from: from});
195 // 0.1] Ask server for room composition:
196 const funcPollClients = () => {
197 this.st.conn.send(JSON.stringify({code:"pollclients"}));
199 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
201 else //socket not ready yet (initial loading)
202 this.st.conn.onopen = funcPollClients;
203 this.st.conn.onmessage = this.socketMessageListener;
204 const socketCloseListener = () => {
205 store.socketCloseListener(); //reinitialize connexion (in store.js)
206 this.st.conn.addEventListener('message', this.socketMessageListener);
207 this.st.conn.addEventListener('close', socketCloseListener);
209 this.st.conn.onclose = socketCloseListener;
213 filterChallenges: function(type) {
214 return this.challenges.filter(c => c.type == type);
216 filterGames: function(type) {
217 return this.games.filter(g => g.type == type);
219 classifyObject: function(o) { //challenge or game
220 // Heuristic: should work for most cases... (TODO)
221 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
223 showGame: function(g) {
224 // NOTE: we are an observer, since only games I don't play are shown here
225 // ==> Moves sent by connected remote player(s) if live game
226 let url = "/game/" + g.id;
227 if (g.type == "live")
228 url += "?rid=" + g.rid;
229 this.$router.push(url);
231 getVname: function(vid) {
232 const variant = this.st.variants.find(v => v.id == vid);
233 // this.st.variants might be uninitialized (variant == null)
234 return (!!variant ? variant.name : "");
236 whatPlayerDoes: function(p) {
237 if (this.games.some(g => g.type == "live"
238 && g.players.some(pl => pl.sid == p.sid)))
242 return "Challenge"; //player is available
244 sendSomethingTo: function(to, code, obj, warnDisconnected) {
245 const doSend = (code, obj, sid) => {
246 this.st.conn.send(JSON.stringify(Object.assign(
255 // Challenge with targeted players
257 Object.keys(this.people).find(sid => this.people[sid].name == to);
260 if (!!warnDisconnected)
261 alert("Warning: " + pname + " is not connected");
264 doSend(code, obj, targetSid);
268 // Open challenge: send to all connected players (except us)
269 Object.keys(this.people).forEach(sid => {
270 if (sid != this.st.user.sid)
271 doSend(code, obj, sid);
276 socketMessageListener: function(msg) {
277 const data = JSON.parse(msg.data);
281 alert("Warning: duplicate 'offline' connection");
283 // 0.2] Receive clients list (just socket IDs)
286 data.sockIds.forEach(sid => {
287 this.$set(this.people, sid, {id:0, name:""});
288 // Ask identity, challenges and game(s)
289 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
290 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
292 // Also ask current games to all playing peers (TODO: some design issue)
293 this.st.conn.send(JSON.stringify({code:"askgames"}));
298 // Request for identification: reply if I'm not anonymous
299 if (this.st.user.id > 0)
301 this.st.conn.send(JSON.stringify({code:"identity",
303 // NOTE: decompose to avoid revealing email
304 name: this.st.user.name,
305 sid: this.st.user.sid,
314 this.$set(this.people, data.user.sid,
315 {id: data.user.id, name: data.user.name});
320 // Send my current live challenge (if any)
321 const cIdx = this.challenges
322 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
325 const c = this.challenges[cIdx];
328 // Minimal challenge informations: (from not required)
333 timeControl: c.timeControl
335 this.st.conn.send(JSON.stringify({code:"challenge",
336 chall:myChallenge, target:data.from}));
342 // Receive challenge from some player (+sid)
343 let newChall = data.chall;
344 newChall.type = this.classifyObject(data.chall);
346 Object.assign({sid:data.from}, this.people[data.from]);
347 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
348 newChall.vname = this.getVname(newChall.vid);
349 this.challenges.push(newChall);
354 // Receive game from some player (+sid)
355 // NOTE: it may be correspondance (if newgame while we are connected)
356 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
358 let newGame = data.game;
359 newGame.type = this.classifyObject(data.game);
360 newGame.vname = this.getVname(data.game.vid);
361 newGame.rid = data.from;
363 this.games.push(newGame);
369 // TODO: next line required ?!
370 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
371 // New game just started: data contain all information
372 if (this.classifyObject(data.gameInfo) == "live")
373 this.startNewGame(data.gameInfo);
376 this.infoMessage = "New game started: " +
377 "<a href='#/game/" + data.gameInfo.id + "'>" +
378 "#/game/" + data.gameInfo.id + "</a>";
379 let modalBox = document.getElementById("modalInfo");
380 modalBox.checked = true;
381 setTimeout(() => { modalBox.checked = false; }, 3000);
385 case "refusechallenge":
387 alert(this.people[data.from].name + " declined your challenge");
388 ArrayFun.remove(this.challenges, c => c.id == data.cid);
391 case "deletechallenge":
393 // NOTE: the challenge may be already removed
394 ArrayFun.remove(this.challenges, c => c.id == data.cid);
395 localStorage.removeItem("challenge"); //in case of
400 this.$set(this.people, data.from, {name:"", id:0});
401 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
402 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
403 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
408 this.$delete(this.people, data.from);
409 // Also remove all challenges sent by this player:
410 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
411 // And all live games where he plays and no other opponent is online
412 ArrayFun.remove(this.games, g =>
413 g.type == "live" && (g.players.every(p => p.sid == data.from
414 || !this.people[p.sid])), "all");
419 // Challenge lifecycle:
420 tryChallenge: function(player) {
422 return; //anonymous players cannot be challenged
423 this.newchallenge.to = player.name;
424 doClick("modalNewgame");
426 challOrWatch: function(p, e) {
427 switch (e.target.innerHTML)
430 this.tryChallenge(p);
433 // NOTE: this search for game was already done for rendering
434 this.showGame(this.games.find(
435 g => g.type=="live" && g.players.some(pl => pl.sid == p.sid)));
439 newChallenge: async function() {
440 const vname = this.getVname(this.newchallenge.vid);
441 const vModule = await import("@/variants/" + vname + ".js");
442 window.V = vModule.VariantRules;
443 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
444 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
445 const error = checkChallenge(this.newchallenge);
448 const ctype = this.classifyObject(this.newchallenge);
449 if (ctype == "corr" && this.st.user.id <= 0)
450 return alert("Please log in to play correspondance games");
451 // NOTE: "from" information is not required here
452 let chall = Object.assign({}, this.newchallenge);
453 const finishAddChallenge = (cid,warnDisconnected) => {
454 chall.id = cid || "c" + getRandString();
455 // Send challenge to peers (if connected)
456 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
457 chall.added = Date.now();
458 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
461 chall.from = { //decompose to avoid revealing email
462 sid: this.st.user.sid,
464 name: this.st.user.name,
466 this.challenges.push(chall);
468 localStorage.setItem("challenge", JSON.stringify(chall));
469 document.getElementById("modalNewgame").checked = false;
471 const cIdx = this.challenges.findIndex(
472 c => c.from.sid == this.st.user.sid && c.type == ctype);
475 // Delete current challenge (will be replaced now)
476 this.sendSomethingTo(this.challenges[cIdx].to,
477 "deletechallenge", {cid:this.challenges[cIdx].id});
483 {id: this.challenges[cIdx].id}
486 this.challenges.splice(cIdx, 1);
490 // Live challenges have a random ID
491 finishAddChallenge(null, "warnDisconnected");
495 // Correspondance game: send challenge to server
500 response => { finishAddChallenge(response.cid); }
504 clickChallenge: function(c) {
505 const myChallenge = (c.from.sid == this.st.user.sid //live
506 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
509 if (c.type == "corr" && this.st.user.id <= 0)
510 return alert("Please log in to accept corr challenges");
512 if (!!c.to) //c.to == this.st.user.name (connected)
514 // TODO: if special FEN, show diagram after loading variant
515 c.accepted = confirm("Accept challenge?");
519 c.seat = { //again, avoid c.seat = st.user to not reveal email
520 sid: this.st.user.sid,
522 name: this.st.user.name,
528 this.st.conn.send(JSON.stringify({
529 code: "refusechallenge",
530 cid: c.id, target: c.from.sid}));
535 if (c.type == "corr")
544 localStorage.removeItem("challenge");
546 // In (almost) all cases, the challenge is consumed:
547 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
548 // NOTE: deletechallenge event might be redundant (but it's easier this way)
549 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
551 // NOTE: when launching game, the challenge is already deleted
552 launchGame: async function(c) {
553 const vModule = await import("@/variants/" + c.vname + ".js");
554 window.V = vModule.VariantRules;
555 // These game informations will be sent to other players
559 fen: c.fen || V.GenRandInitFen(),
560 players: shuffle([c.from, c.seat]), //white then black
562 vname: c.vname, //theoretically vid is enough, but much easier with vname
563 timeControl: c.timeControl,
565 let target = c.from.sid; //may not be defined if corr + offline opp
568 target = Object.keys(this.people).find(sid =>
569 this.people[sid].id == c.from.id);
571 const tryNotifyOpponent = () => {
572 if (!!target) //opponent is online
574 this.st.conn.send(JSON.stringify({code:"newgame",
575 gameInfo:gameInfo, target:target, cid:c.id}));
578 if (c.type == "live")
581 this.startNewGame(gameInfo);
583 else //corr: game only on server
588 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
590 gameInfo.id = response.gameId;
592 this.$router.push("/game/" + response.gameId);
596 // Send game info to everyone except opponent (and me)
597 this.st.conn.send(JSON.stringify({code:"game",
598 game: { //minimal game info:
600 players: gameInfo.players.map(p => p.name),
602 timeControl: gameInfo.timeControl,
606 // NOTE: for live games only (corr games start on the server)
607 startNewGame: function(gameInfo) {
608 const game = Object.assign({}, gameInfo, {
609 // (other) Game infos: constant
610 fenStart: gameInfo.fen,
612 // Game state (including FEN): will be updated
614 clocks: [-1, -1], //-1 = unstarted
615 initime: [0, 0], //initialized later
618 GameStorage.add(game);
619 if (this.st.settings.sound >= 1)
620 new Audio("/sounds/newgame.mp3").play().catch(err => {});
621 this.$router.push("/game/" + gameInfo.id);
627 <style lang="sass" scoped>
630 margin: 10px auto 5px auto
637 @media screen and (max-width: 767px)