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
37 button(@click="cdisplay='live'") Live Challenges
38 button(@click="cdisplay='corr'") Correspondance challenges
39 ChallengeList(v-show="cdisplay=='live'"
40 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
41 ChallengeList(v-show="cdisplay=='corr'"
42 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
45 button(@click="pdisplay='players'") Players
46 button(@click="pdisplay='chat'") Chat
47 #players(v-show="pdisplay=='players'")
48 p(v-for="p in uniquePlayers")
49 span(:class="{anonymous: !!p.count}")
50 | {{ (p.name || '@nonymous') + (!!p.count ? " ("+p.count+")" : "") }}
51 button.player-action(v-if="!p.count && p.name != st.user.name"
52 @click="challOrWatch(p,$event)")
53 | {{ whatPlayerDoes(p) }}
54 #chat(v-show="pdisplay=='chat'")
58 button(@click="gdisplay='live'") Live games
59 button(@click="gdisplay='corr'") Correspondance games
60 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
61 @show-game="showGame")
62 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
63 @show-game="showGame")
67 import { store } from "@/store";
68 import { checkChallenge } from "@/data/challengeCheck";
69 import { ArrayFun } from "@/utils/array";
70 import { ajax } from "@/utils/ajax";
71 import { getRandString, shuffle } from "@/utils/alea";
72 import Chat from "@/components/Chat.vue";
73 import GameList from "@/components/GameList.vue";
74 import ChallengeList from "@/components/ChallengeList.vue";
75 import { GameStorage } from "@/utils/gameStorage";
86 cdisplay: "live", //or corr
87 pdisplay: "players", //or chat
91 people: {}, //people in main hall
96 to: "", //name of challenged player (if any)
97 timeControl: "", //"2m+2s" ...etc
102 // st.variants changes only once, at loading from [] to [...]
103 "st.variants": function(variantArray) {
104 // Set potential challenges and games variant names:
105 this.challenges.forEach(c => {
107 c.vname = this.getVname(c.vid);
109 this.games.forEach(g => {
111 g.vname = this.getVname(g.vid);
116 uniquePlayers: function() {
117 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
118 let anonymous = {name:"", count:0};
120 Object.values(this.people).forEach(p => {
123 // We don't count registered users connections: either they are here or not.
124 if (!playerList[p.id])
125 playerList[p.id] = {name: p.name};
130 if (anonymous.count > 0)
131 playerList[0] = anonymous;
132 return Object.values(playerList);
135 created: function() {
136 // Always add myself to players' list
137 const my = this.st.user;
138 this.$set(this.people, my.sid, {id:my.id, name:my.name});
139 // Retrieve live challenge (not older than 30 minute) if any:
140 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
143 if ((Date.now() - chall.added)/1000 <= 30*60)
144 this.challenges.push(chall);
146 localStorage.removeItem("challenge");
148 // Ask server for current corr games (all but mines)
152 {uid: this.st.user.id, excluded: true},
154 this.games = this.games.concat(response.games.map(g => {
155 const type = this.classifyObject(g);
156 const vname = this.getVname(g.vid);
157 return Object.assign({}, g, {type: type, vname: vname});
161 // Also ask for corr challenges (open + sent to me)
165 {uid: this.st.user.id},
167 // Gather all senders names, and then retrieve full identity:
168 // (TODO [perf]: some might be online...)
169 const uids = response.challenges.map(c => { return c.uid });
172 { ids: uids.join(",") },
175 response2.users.forEach(u => {names[u.id] = u.name});
176 this.challenges = this.challenges.concat(
177 response.challenges.map(c => {
178 // (just players names in fact)
179 const from = {name: names[c.uid], id: c.uid};
180 const type = this.classifyObject(c);
181 const vname = this.getVname(c.vid);
182 return Object.assign({}, c, {type: type, vname: vname, from: from});
189 // 0.1] Ask server for room composition:
190 const funcPollClients = () => {
191 this.st.conn.send(JSON.stringify({code:"pollclients"}));
193 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
195 else //socket not ready yet (initial loading)
196 this.st.conn.onopen = funcPollClients;
197 this.st.conn.onmessage = this.socketMessageListener;
198 const socketCloseListener = () => {
199 store.socketCloseListener(); //reinitialize connexion (in store.js)
200 this.st.conn.addEventListener('message', this.socketMessageListener);
201 this.st.conn.addEventListener('close', socketCloseListener);
203 this.st.conn.onclose = socketCloseListener;
207 filterChallenges: function(type) {
208 return this.challenges.filter(c => c.type == type);
210 filterGames: function(type) {
211 return this.games.filter(g => g.type == type);
213 classifyObject: function(o) { //challenge or game
214 // Heuristic: should work for most cases... (TODO)
215 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
217 showGame: function(g) {
218 // NOTE: we are an observer, since only games I don't play are shown here
219 // ==> Moves sent by connected remote player(s) if live game
220 let url = "/game/" + g.id;
221 if (g.type == "live")
222 url += "?rid=" + g.rid;
223 this.$router.push(url);
225 getVname: function(vid) {
226 const variant = this.st.variants.find(v => v.id == vid);
227 // this.st.variants might be uninitialized (variant == null)
228 return (!!variant ? variant.name : "");
230 whatPlayerDoes: function(p) {
231 if (this.games.some(g => g.type == "live"
232 && g.players.some(pl => pl.sid == p.sid)))
236 return "Challenge"; //player is available
238 sendSomethingTo: function(to, code, obj, warnDisconnected) {
239 const doSend = (code, obj, sid) => {
240 this.st.conn.send(JSON.stringify(Object.assign(
249 // Challenge with targeted players
251 Object.keys(this.people).find(sid => this.people[sid].name == to);
254 if (!!warnDisconnected)
255 alert("Warning: " + pname + " is not connected");
258 doSend(code, obj, targetSid);
262 // Open challenge: send to all connected players (except us)
263 Object.keys(this.people).forEach(sid => {
264 if (sid != this.st.user.sid)
265 doSend(code, obj, sid);
270 socketMessageListener: function(msg) {
271 const data = JSON.parse(msg.data);
275 alert("Warning: duplicate 'offline' connection");
277 // 0.2] Receive clients list (just socket IDs)
280 data.sockIds.forEach(sid => {
281 this.$set(this.people, sid, {id:0, name:""});
282 // Ask identity, challenges and game(s)
283 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
284 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
286 // Also ask current games to all playing peers (TODO: some design issue)
287 this.st.conn.send(JSON.stringify({code:"askgames"}));
292 // Request for identification: reply if I'm not anonymous
293 if (this.st.user.id > 0)
295 this.st.conn.send(JSON.stringify({code:"identity",
297 // NOTE: decompose to avoid revealing email
298 name: this.st.user.name,
299 sid: this.st.user.sid,
308 this.$set(this.people, data.user.sid,
309 {id: data.user.id, name: data.user.name});
314 // Send my current live challenge (if any)
315 const cIdx = this.challenges
316 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
319 const c = this.challenges[cIdx];
322 // Minimal challenge informations: (from not required)
327 timeControl: c.timeControl
329 this.st.conn.send(JSON.stringify({code:"challenge",
330 chall:myChallenge, target:data.from}));
336 // Receive challenge from some player (+sid)
337 let newChall = data.chall;
338 newChall.type = this.classifyObject(data.chall);
340 Object.assign({sid:data.from}, this.people[data.from]);
341 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
342 newChall.vname = this.getVname(newChall.vid);
343 this.challenges.push(newChall);
348 // Receive game from some player (+sid)
349 // NOTE: it may be correspondance (if newgame while we are connected)
350 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
352 let newGame = data.game;
353 newGame.type = this.classifyObject(data.game);
354 newGame.vname = this.getVname(data.game.vid);
355 newGame.rid = data.from;
357 this.games.push(newGame);
363 // TODO: next line required ?!
364 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
365 // New game just started: data contain all information
366 if (this.classifyObject(data.gameInfo) == "live")
367 this.startNewGame(data.gameInfo);
370 this.infoMessage = "New game started: " +
371 "<a href='#/game/" + data.gameInfo.id + "'>" +
372 "#/game/" + data.gameInfo.id + "</a>";
373 let modalBox = document.getElementById("modalInfo");
374 modalBox.checked = true;
375 setTimeout(() => { modalBox.checked = false; }, 3000);
379 case "refusechallenge":
381 alert(this.people[data.from].name + " declined your challenge");
382 ArrayFun.remove(this.challenges, c => c.id == data.cid);
385 case "deletechallenge":
387 // NOTE: the challenge may be already removed
388 ArrayFun.remove(this.challenges, c => c.id == data.cid);
389 localStorage.removeItem("challenge"); //in case of
394 this.$set(this.people, data.from, {name:"", id:0});
395 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
396 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
397 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
402 this.$delete(this.people, data.from);
403 // Also remove all challenges sent by this player:
404 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
405 // And all live games where he plays and no other opponent is online
406 ArrayFun.remove(this.games, g =>
407 g.type == "live" && (g.players.every(p => p.sid == data.from
408 || !this.people[p.sid])), "all");
413 // Challenge lifecycle:
414 tryChallenge: function(player) {
416 return; //anonymous players cannot be challenged
417 this.newchallenge.to = player.name;
418 doClick("modalNewgame");
420 challOrWatch: function(p, e) {
421 switch (e.target.innerHTML)
424 this.tryChallenge(p);
427 // NOTE: this search for game was already done for rendering
428 this.showGame(this.games.find(
429 g => g.type=="live" && g.players.some(pl => pl.sid == p.sid)));
433 newChallenge: async function() {
434 const vname = this.getVname(this.newchallenge.vid);
435 const vModule = await import("@/variants/" + vname + ".js");
436 window.V = vModule.VariantRules;
437 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
438 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
439 const error = checkChallenge(this.newchallenge);
442 const ctype = this.classifyObject(this.newchallenge);
443 if (ctype == "corr" && this.st.user.id <= 0)
444 return alert("Please log in to play correspondance games");
445 // NOTE: "from" information is not required here
446 let chall = Object.assign({}, this.newchallenge);
447 const finishAddChallenge = (cid,warnDisconnected) => {
448 chall.id = cid || "c" + getRandString();
449 // Send challenge to peers (if connected)
450 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
451 chall.added = Date.now();
452 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
455 chall.from = { //decompose to avoid revealing email
456 sid: this.st.user.sid,
458 name: this.st.user.name,
460 this.challenges.push(chall);
462 localStorage.setItem("challenge", JSON.stringify(chall));
463 document.getElementById("modalNewgame").checked = false;
465 const cIdx = this.challenges.findIndex(
466 c => c.from.sid == this.st.user.sid && c.type == ctype);
469 // Delete current challenge (will be replaced now)
470 this.sendSomethingTo(this.challenges[cIdx].to,
471 "deletechallenge", {cid:this.challenges[cIdx].id});
477 {id: this.challenges[cIdx].id}
480 this.challenges.splice(cIdx, 1);
484 // Live challenges have a random ID
485 finishAddChallenge(null, "warnDisconnected");
489 // Correspondance game: send challenge to server
494 response => { finishAddChallenge(response.cid); }
498 clickChallenge: function(c) {
499 const myChallenge = (c.from.sid == this.st.user.sid //live
500 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
503 if (c.type == "corr" && this.st.user.id <= 0)
504 return alert("Please log in to accept corr challenges");
506 if (!!c.to) //c.to == this.st.user.name (connected)
508 // TODO: if special FEN, show diagram after loading variant
509 c.accepted = confirm("Accept challenge?");
513 c.seat = { //again, avoid c.seat = st.user to not reveal email
514 sid: this.st.user.sid,
516 name: this.st.user.name,
522 this.st.conn.send(JSON.stringify({
523 code: "refusechallenge",
524 cid: c.id, target: c.from.sid}));
529 if (c.type == "corr")
538 localStorage.removeItem("challenge");
540 // In (almost) all cases, the challenge is consumed:
541 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
542 // NOTE: deletechallenge event might be redundant (but it's easier this way)
543 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
545 // NOTE: when launching game, the challenge is already deleted
546 launchGame: async function(c) {
547 const vModule = await import("@/variants/" + c.vname + ".js");
548 window.V = vModule.VariantRules;
549 // These game informations will be sent to other players
553 fen: c.fen || V.GenRandInitFen(),
554 players: shuffle([c.from, c.seat]), //white then black
556 vname: c.vname, //theoretically vid is enough, but much easier with vname
557 timeControl: c.timeControl,
559 let target = c.from.sid; //may not be defined if corr + offline opp
562 target = Object.keys(this.people).find(sid =>
563 this.people[sid].id == c.from.id);
565 const tryNotifyOpponent = () => {
566 if (!!target) //opponent is online
568 this.st.conn.send(JSON.stringify({code:"newgame",
569 gameInfo:gameInfo, target:target, cid:c.id}));
572 if (c.type == "live")
575 this.startNewGame(gameInfo);
577 else //corr: game only on server
582 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
584 gameInfo.id = response.gameId;
586 this.$router.push("/game/" + response.gameId);
590 // Send game info to everyone except opponent (and me)
591 this.st.conn.send(JSON.stringify({code:"game",
592 game: { //minimal game info:
594 players: gameInfo.players.map(p => p.name),
596 timeControl: gameInfo.timeControl,
600 // NOTE: for live games only (corr games start on the server)
601 startNewGame: function(gameInfo) {
602 const game = Object.assign({}, gameInfo, {
603 // (other) Game infos: constant
604 fenStart: gameInfo.fen,
606 // Game state (including FEN): will be updated
608 clocks: [-1, -1], //-1 = unstarted
609 initime: [0, 0], //initialized later
612 GameStorage.add(game);
613 if (this.st.settings.sound >= 1)
614 new Audio("/sounds/newgame.mp3").play().catch(err => {});
615 this.$router.push("/game/" + gameInfo.id);
621 <style lang="sass" scoped>
624 margin: 10px auto 5px auto
631 @media screen and (max-width: 767px)