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
36 button(@click="(e) => setDisplay('c','live',e)" class="active")
38 button(@click="(e) => setDisplay('c','corr',e)")
39 | Correspondance challenges
40 ChallengeList(v-show="cdisplay=='live'"
41 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
42 ChallengeList(v-show="cdisplay=='corr'"
43 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
45 h3.text-center Who's there?
47 p(v-for="p in Object.values(people)" v-if="!!p.name")
50 v-if="p.name != st.user.name"
51 @click="challOrWatch(p,$event)"
53 | {{ whatPlayerDoes(p) }}
54 p.anonymous @nonymous ({{ anonymousCount }})
60 button(@click="(e) => setDisplay('g','live',e)" class="active")
62 button(@click="(e) => setDisplay('g','corr',e)")
63 | Correspondance games
64 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
65 @show-game="showGame")
66 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
67 @show-game="showGame")
71 import { store } from "@/store";
72 import { checkChallenge } from "@/data/challengeCheck";
73 import { ArrayFun } from "@/utils/array";
74 import { ajax } from "@/utils/ajax";
75 import { getRandString, shuffle } from "@/utils/alea";
76 import Chat from "@/components/Chat.vue";
77 import GameList from "@/components/GameList.vue";
78 import ChallengeList from "@/components/ChallengeList.vue";
79 import { GameStorage } from "@/utils/gameStorage";
90 cdisplay: "live", //or corr
91 pdisplay: "players", //or chat
95 people: {}, //people in main hall
100 to: "", //name of challenged player (if any)
101 timeControl: "", //"2m+2s" ...etc
106 // st.variants changes only once, at loading from [] to [...]
107 "st.variants": function(variantArray) {
108 // Set potential challenges and games variant names:
109 this.challenges.forEach(c => {
111 c.vname = this.getVname(c.vid);
113 this.games.forEach(g => {
115 g.vname = this.getVname(g.vid);
120 anonymousCount: function() {
122 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
126 created: function() {
127 // Always add myself to players' list
128 const my = this.st.user;
129 this.$set(this.people, my.sid, {id:my.id, name:my.name});
130 // Retrieve live challenge (not older than 30 minute) if any:
131 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
134 // NOTE: a challenge survives 3 minutes, for potential connection issues
135 if ((Date.now() - chall.added)/1000 <= 3*60)
137 chall.added = Date.now(); //update added time, for next disconnect...
138 this.challenges.push(chall);
139 localStorage.setItem("challenge", JSON.stringify(chall));
142 localStorage.removeItem("challenge");
144 // Ask server for current corr games (all but mines)
148 {uid: this.st.user.id, excluded: true},
150 this.games = this.games.concat(response.games.map(g => {
151 const type = this.classifyObject(g);
152 const vname = this.getVname(g.vid);
153 return Object.assign({}, g, {type: type, vname: vname});
157 // Also ask for corr challenges (open + sent to me)
161 {uid: this.st.user.id},
163 // Gather all senders names, and then retrieve full identity:
164 // (TODO [perf]: some might be online...)
165 const uids = response.challenges.map(c => { return c.uid });
168 { ids: uids.join(",") },
171 response2.users.forEach(u => {names[u.id] = u.name});
172 this.challenges = this.challenges.concat(
173 response.challenges.map(c => {
174 // (just players names in fact)
175 const from = {name: names[c.uid], id: c.uid};
176 const type = this.classifyObject(c);
177 const vname = this.getVname(c.vid);
178 return Object.assign({}, c, {type: type, vname: vname, from: from});
185 // 0.1] Ask server for room composition:
186 const funcPollClients = () => {
187 // Same strategy as in Game.vue: send connection
188 // after we're sure WebSocket is initialized
189 this.st.conn.send(JSON.stringify({code:"connect"}));
190 this.st.conn.send(JSON.stringify({code:"pollclients"}));
192 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
194 else //socket not ready yet (initial loading)
195 this.st.conn.onopen = funcPollClients;
196 this.st.conn.onmessage = this.socketMessageListener;
197 const socketCloseListener = () => {
198 store.socketCloseListener(); //reinitialize connexion (in store.js)
199 this.st.conn.addEventListener('message', this.socketMessageListener);
200 this.st.conn.addEventListener('close', socketCloseListener);
202 this.st.conn.onclose = socketCloseListener;
206 filterChallenges: function(type) {
207 return this.challenges.filter(c => c.type == type);
209 filterGames: function(type) {
210 return this.games.filter(g => g.type == type);
212 classifyObject: function(o) { //challenge or game
213 // Heuristic: should work for most cases... (TODO)
214 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
216 showGame: function(g) {
217 // NOTE: we are an observer, since only games I don't play are shown here
218 // ==> Moves sent by connected remote player(s) if live game
219 let url = "/game/" + g.id;
220 if (g.type == "live")
221 url += "?rid=" + g.rid;
222 this.$router.push(url);
224 setDisplay: function(letter, type, e) {
225 this[letter + "display"] = type;
226 e.target.classList.add("active");
227 if (!!e.target.previousElementSibling)
228 e.target.previousElementSibling.classList.remove("active");
230 e.target.nextElementSibling.classList.remove("active");
232 getVname: function(vid) {
233 const variant = this.st.variants.find(v => v.id == vid);
234 // this.st.variants might be uninitialized (variant == null)
235 return (!!variant ? variant.name : "");
237 whatPlayerDoes: function(p) {
238 if (this.games.some(g => g.type == "live"
239 && g.players.some(pl => pl.sid == p.sid)))
243 return "Challenge"; //player is available
245 sendSomethingTo: function(to, code, obj, warnDisconnected) {
246 const doSend = (code, obj, sid) => {
247 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: " + to + " is not connected");
265 doSend(code, obj, targetSid);
269 // Open challenge: send to all connected players (me excepted)
270 Object.keys(this.people).forEach(sid => {
271 if (sid != this.st.user.sid)
272 doSend(code, obj, sid);
278 socketMessageListener: function(msg) {
279 const data = JSON.parse(msg.data);
283 alert("Warning: duplicate 'offline' connection");
285 // 0.2] Receive clients list (just socket IDs)
288 data.sockIds.forEach(sid => {
289 this.$set(this.people, sid, {id:0, name:""});
290 // Ask identity, challenges and game(s)
291 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
292 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
294 // Also ask current games to all playing peers (TODO: some design issue)
295 this.st.conn.send(JSON.stringify({code:"askgames"}));
300 // Request for identification: reply if I'm not anonymous
301 if (this.st.user.id > 0)
303 this.st.conn.send(JSON.stringify({code:"identity",
305 // NOTE: decompose to avoid revealing email
306 name: this.st.user.name,
307 sid: this.st.user.sid,
316 this.$set(this.people, data.user.sid,
317 {id: data.user.id, name: data.user.name});
322 // Send my current live challenge (if any)
323 const cIdx = this.challenges.findIndex(c =>
324 c.from.sid == this.st.user.sid && c.type == "live");
327 const c = this.challenges[cIdx];
330 // Only share targeted challenges to the targets:
331 const toSid = Object.keys(this.people).find(k =>
332 this.people[k].name == c.to);
333 if (toSid != data.from)
338 // Minimal challenge informations: (from not required)
343 timeControl: c.timeControl,
345 this.st.conn.send(JSON.stringify({code:"challenge",
346 chall:myChallenge, target:data.from}));
352 // Receive challenge from some player (+sid)
353 let newChall = data.chall;
354 newChall.type = this.classifyObject(data.chall);
356 Object.assign({sid:data.from}, this.people[data.from]);
357 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
358 newChall.vname = this.getVname(newChall.vid);
359 this.challenges.push(newChall);
364 // Receive game from some player (+sid)
365 // NOTE: it may be correspondance (if newgame while we are connected)
366 // If duplicate found: select rid (remote ID) at random
367 let game = this.games.find(g => g.id == data.game.id);
368 if (!!game && Math.random() < 0.5)
369 game.rid = data.from;
372 let newGame = data.game;
373 newGame.type = this.classifyObject(data.game);
374 newGame.vname = this.getVname(data.game.vid);
375 newGame.rid = data.from;
377 this.games.push(newGame);
383 // TODO: next line required ?!
384 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
385 // New game just started: data contain all information
386 if (this.classifyObject(data.gameInfo) == "live")
387 this.startNewGame(data.gameInfo);
390 this.infoMessage = "New game started: " +
391 "<a href='#/game/" + data.gameInfo.id + "'>" +
392 "#/game/" + data.gameInfo.id + "</a>";
393 let modalBox = document.getElementById("modalInfo");
394 modalBox.checked = true;
395 setTimeout(() => { modalBox.checked = false; }, 3000);
399 case "refusechallenge":
401 ArrayFun.remove(this.challenges, c => c.id == data.cid);
402 localStorage.removeItem("challenge");
403 alert(this.people[data.from].name + " declined your challenge");
406 case "deletechallenge":
408 // NOTE: the challenge may be already removed
409 ArrayFun.remove(this.challenges, c => c.id == data.cid);
410 localStorage.removeItem("challenge"); //in case of
415 this.$set(this.people, data.from, {name:"", id:0});
416 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
417 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
418 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
423 this.$delete(this.people, data.from);
424 // Also remove all challenges sent by this player:
425 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
426 // And all live games where he plays and no other opponent is online
427 ArrayFun.remove(this.games, g =>
428 g.type == "live" && (g.players.every(p => p.sid == data.from
429 || !this.people[p.sid])), "all");
434 // Challenge lifecycle:
435 tryChallenge: function(player) {
437 return; //anonymous players cannot be challenged
438 this.newchallenge.to = player.name;
439 doClick("modalNewgame");
441 challOrWatch: function(p, e) {
442 switch (e.target.innerHTML)
445 this.tryChallenge(p);
448 // NOTE: this search for game was already done for rendering
449 this.showGame(this.games.find(
450 g => g.type=="live" && g.players.some(pl => pl.sid == p.sid)));
454 newChallenge: async function() {
455 const vname = this.getVname(this.newchallenge.vid);
456 const vModule = await import("@/variants/" + vname + ".js");
457 window.V = vModule.VariantRules;
458 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
459 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
460 const error = checkChallenge(this.newchallenge);
463 const ctype = this.classifyObject(this.newchallenge);
464 if (ctype == "corr" && this.st.user.id <= 0)
465 return alert("Please log in to play correspondance games");
466 // NOTE: "from" information is not required here
467 let chall = Object.assign({}, this.newchallenge);
468 const finishAddChallenge = (cid,warnDisconnected) => {
469 chall.id = cid || "c" + getRandString();
470 // Send challenge to peers (if connected)
471 const isSent = this.sendSomethingTo(chall.to, "challenge",
472 {chall:chall}, !!warnDisconnected);
475 // Remove old challenge if any (only one at a time):
476 const cIdx = this.challenges.findIndex(c =>
477 c.from.sid == this.st.user.sid && c.type == ctype);
480 // Delete current challenge (will be replaced now)
481 this.sendSomethingTo(this.challenges[cIdx].to,
482 "deletechallenge", {cid:this.challenges[cIdx].id});
488 {id: this.challenges[cIdx].id}
491 this.challenges.splice(cIdx, 1);
493 // Add new challenge:
494 chall.added = Date.now();
495 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
498 chall.from = { //decompose to avoid revealing email
499 sid: this.st.user.sid,
501 name: this.st.user.name,
503 this.challenges.push(chall);
505 localStorage.setItem("challenge", JSON.stringify(chall));
506 document.getElementById("modalNewgame").checked = false;
510 // Live challenges have a random ID
511 finishAddChallenge(null, "warnDisconnected");
515 // Correspondance game: send challenge to server
520 response => { finishAddChallenge(response.cid); }
524 clickChallenge: function(c) {
525 const myChallenge = (c.from.sid == this.st.user.sid //live
526 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
529 if (c.type == "corr" && this.st.user.id <= 0)
530 return alert("Please log in to accept corr challenges");
532 if (!!c.to) //c.to == this.st.user.name (connected)
534 // TODO: if special FEN, show diagram after loading variant
535 c.accepted = confirm("Accept challenge?");
539 c.seat = { //again, avoid c.seat = st.user to not reveal email
540 sid: this.st.user.sid,
542 name: this.st.user.name,
548 this.st.conn.send(JSON.stringify({
549 code: "refusechallenge",
550 cid: c.id, target: c.from.sid}));
552 // TODO: refactor the "sendSomethingTo()" function
554 this.sendSomethingTo(null, "deletechallenge", {cid:c.id});
557 this.st.conn.send(JSON.stringify({
558 code:"deletechallenge", target: c.from.sid, cid: c.id}));
563 if (c.type == "corr")
572 localStorage.removeItem("challenge");
573 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
575 // In all cases, the challenge is consumed:
576 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
578 // NOTE: when launching game, the challenge is already deleted
579 launchGame: async function(c) {
580 const vModule = await import("@/variants/" + c.vname + ".js");
581 window.V = vModule.VariantRules;
582 // These game informations will be sent to other players
586 fen: c.fen || V.GenRandInitFen(),
587 players: shuffle([c.from, c.seat]), //white then black
589 vname: c.vname, //theoretically vid is enough, but much easier with vname
590 timeControl: c.timeControl,
592 let oppsid = c.from.sid; //may not be defined if corr + offline opp
595 oppsid = Object.keys(this.people).find(sid =>
596 this.people[sid].id == c.from.id);
598 const tryNotifyOpponent = () => {
599 if (!!oppsid) //opponent is online
601 this.st.conn.send(JSON.stringify({code:"newgame",
602 gameInfo:gameInfo, target:oppsid, cid:c.id}));
605 if (c.type == "live")
607 // NOTE: in this case we are sure opponent is online
609 this.startNewGame(gameInfo);
611 else //corr: game only on server
616 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
618 gameInfo.id = response.gameId;
620 this.$router.push("/game/" + response.gameId);
624 // Send game info to everyone except opponent (and me)
625 Object.keys(this.people).forEach(sid => {
626 if (![this.st.user.sid,oppsid].includes(sid))
628 this.st.conn.send(JSON.stringify({code:"game",
629 game: { //minimal game info:
631 players: gameInfo.players,
633 timeControl: gameInfo.timeControl,
639 // NOTE: for live games only (corr games start on the server)
640 startNewGame: function(gameInfo) {
641 const game = Object.assign({}, gameInfo, {
642 // (other) Game infos: constant
643 fenStart: gameInfo.fen,
645 // Game state (including FEN): will be updated
647 clocks: [-1, -1], //-1 = unstarted
648 initime: [0, 0], //initialized later
651 GameStorage.add(game);
652 if (this.st.settings.sound >= 1)
653 new Audio("/sounds/newgame.mp3").play().catch(err => {});
654 this.$router.push("/game/" + gameInfo.id);
660 <style lang="sass" scoped>
665 margin: 10px auto 5px auto
676 @media screen and (max-width: 767px)