3 input#modalNewgame.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="titleFenedit")
6 label#closeNewgame.modal-close(for="modalNewgame")
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 }}
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"] }}
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
26 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
28 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
29 label(for="challengeSection" aria-hidden="true") Challenges
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
42 button(@click="pdisplay='players'") Players
43 button(@click="pdisplay='chat'") Chat
44 #players(v-show="pdisplay=='players'")
46 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
47 :class="{anonymous: !!p.count}"
49 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
50 #chat(v-show="pdisplay=='chat'")
52 input#gameSection(type="radio" aria-hidden="true" name="accordion")
53 label(for="gameSection" aria-hidden="true") Games
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")
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";
82 cdisplay: "live", //or corr
83 pdisplay: "players", //or chat
87 people: [], //(all) online players
91 to: "", //name of challenged player (if any)
92 timeControl: "", //"2m+2s" ...etc
97 uniquePlayers: function() {
98 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
99 let anonymous = {id:0, name:"@nonymous", count:0};
101 this.people.forEach(p => {
107 if (anonymous.count > 0)
108 playerList.push(anonymous);
112 created: function() {
113 // Always add myself to players' list
114 const my = this.st.user;
115 this.people.push({sid:my.sid, id:my.id, name:my.name});
116 // Retrieve live challenge (not older than 30 minute) if any:
117 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
120 if ((Date.now() - chall.added)/1000 <= 30*60)
121 this.challenges.push(chall);
123 localStorage.removeItem("challenge");
125 if (this.st.user.id > 0)
127 // Ask server for current corr games (all but mines)
131 {uid: this.st.user.id, excluded: true},
133 this.games = this.games.concat(response.games.map(g => {
134 const type = this.classifyObject(g);
135 const vname = this.getVname(g.vid);
136 return Object.assign({}, g, {type: type, vname: vname});
140 // Also ask for corr challenges (open + sent to me)
144 {uid: this.st.user.id},
146 // Gather all senders names, and then retrieve full identity:
147 // (TODO [perf]: some might be online...)
148 const uids = response.challenges.map(c => { return c.uid });
151 { ids: uids.join(",") },
154 response2.users.forEach(u => {names[u.id] = u.name});
155 this.challenges = this.challenges.concat(
156 response.challenges.map(c => {
157 // (just players names in fact)
158 const from = {name: names[c.uid], id: c.uid};
159 const type = this.classifyObject(c);
160 const vname = this.getVname(c.vid);
161 return Object.assign({}, c, {type: type, vname: vname, from: from});
168 // TODO: I don't like this code below; improvement?
169 let retryForVnames = setInterval(() => {
170 if (this.st.variants.length > 0) //variants array is loaded
172 if (this.games.length > 0 && this.games[0].vname == "")
174 // Fix games' vnames:
175 this.games.forEach(g => { g.vname = this.getVname(g.vid); });
177 if (this.challenges.length > 0 && this.challenges[0].vname == "")
179 // Fix challenges' vnames:
180 this.challenges.forEach(c => { c.vname = this.getVname(c.vid); });
182 clearInterval(retryForVnames);
186 // 0.1] Ask server for room composition:
187 const funcPollClients = () => {
188 this.st.conn.send(JSON.stringify({code:"pollclients"}));
190 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
192 else //socket not ready yet (initial loading)
193 this.st.conn.onopen = funcPollClients;
194 this.st.conn.onmessage = this.socketMessageListener;
195 const socketCloseListener = () => {
196 store.socketCloseListener(); //reinitialize connexion (in store.js)
197 this.st.conn.addEventListener('message', this.socketMessageListener);
198 this.st.conn.addEventListener('close', socketCloseListener);
200 this.st.conn.onclose = socketCloseListener;
204 filterChallenges: function(type) {
205 return this.challenges.filter(c => c.type == type);
207 filterGames: function(type) {
208 return this.games.filter(g => g.type == type);
210 classifyObject: function(o) { //challenge or game
211 // Heuristic: should work for most cases... (TODO)
212 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
214 showGame: function(g) {
215 // NOTE: we are an observer, since only games I don't play are shown here
216 // ==> Moves sent by connected remote player(s) if live game
217 let url = "/game/" + g.id;
218 if (g.type == "live")
220 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
221 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
222 url += "?rid=" + remotes[rIdx].sid;
224 this.$router.push(url);
226 // TODO: ...filter(...)[0].name, one-line, just remove this function
227 getVname: function(vid) {
228 const vIdx = this.st.variants.findIndex(v => v.id == vid);
229 return vIdx >= 0 ? this.st.variants[vIdx].name : "";
231 getSid: function(pname) {
232 const pIdx = this.people.findIndex(pl => pl.name == pname);
233 return (pIdx === -1 ? null : this.people[pIdx].sid);
235 getPname: function(sid) {
236 const pIdx = this.people.findIndex(pl => pl.sid == sid);
237 return (pIdx === -1 ? null : this.people[pIdx].name);
239 sendSomethingTo: function(to, code, obj, warnDisconnected) {
240 const doSend = (code, obj, sid) => {
241 this.st.conn.send(JSON.stringify(Object.assign(
250 // Challenge with targeted players
251 const targetSid = this.getSid(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 this.people.forEach(p => {
264 if (p.sid != this.st.user.sid) //only sid is always set
265 doSend(code, obj, p.sid);
270 socketMessageListener: function(msg) {
271 const data = JSON.parse(msg.data);
274 // 0.2] Receive clients list (just socket IDs)
277 data.sockIds.forEach(sid => {
278 this.people.push({sid:sid, id:0, name:""});
279 // Ask identity, challenges and game(s)
280 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
281 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
282 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
288 // Request for identification: reply if I'm not anonymous
289 if (this.st.user.id > 0)
291 this.st.conn.send(JSON.stringify(
292 // people[0] instead of st.user to avoid sending email
293 {code:"identity", user:this.people[0], target:data.from}));
299 // Send my current live challenge (if any)
300 const cIdx = this.challenges
301 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
304 const c = this.challenges[cIdx];
307 // Minimal challenge informations: (from not required)
312 timeControl: c.timeControl
314 this.st.conn.send(JSON.stringify({code:"challenge",
315 chall:myChallenge, target:data.from}));
321 // Send my current live game (if any)
322 GameStorage.getCurrent((game) => {
327 // Minimal game informations:
329 players: game.players.map(p => p.name),
331 timeControl: game.timeControl,
333 this.st.conn.send(JSON.stringify({code:"game",
334 game:myGame, target:data.from}));
341 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
342 this.people[pIdx].id = data.user.id;
343 this.people[pIdx].name = data.user.name;
348 // Receive challenge from some player (+sid)
349 let newChall = data.chall;
350 newChall.type = this.classifyObject(data.chall);
351 const pIdx = this.people.findIndex(p => p.sid == data.from);
352 newChall.from = this.people[pIdx]; //may be anonymous
353 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
354 newChall.vname = this.getVname(newChall.vid);
355 this.challenges.push(newChall);
360 // Receive game from some player (+sid)
361 // NOTE: it may be correspondance (if newgame while we are connected)
362 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
364 let newGame = data.game;
365 newGame.type = this.classifyObject(data.game);
366 newGame.vname = this.getVname(data.game.vid);
367 newGame.rid = data.from;
369 this.games.push(newGame);
375 // TODO: next line required ?!
376 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
377 // New game just started: data contain all information
378 if (this.classifyObject(data.gameInfo) == "live")
379 this.startNewGame(data.gameInfo);
382 // TODO: notify with game link but do not redirect
386 case "refusechallenge":
388 alert(this.getPname(data.from) + " declined your challenge");
389 ArrayFun.remove(this.challenges, c => c.id == data.cid);
392 case "deletechallenge":
394 // NOTE: the challenge may be already removed
395 ArrayFun.remove(this.challenges, c => c.id == data.cid);
396 localStorage.removeItem("challenge"); //in case of
401 this.people.push({name:"", id:0, sid:data.sid});
402 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
403 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
404 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
409 ArrayFun.remove(this.people, p => p.sid == data.sid);
410 // Also remove all challenges sent by this player:
411 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
412 // And all live games where he plays and no other opponent is online
413 ArrayFun.remove(this.games, g =>
414 g.type == "live" && (g.players.every(p => p.sid == data.sid
415 || !this.people.some(pl => pl.sid == p.sid))), "all");
420 // Challenge lifecycle:
421 tryChallenge: function(player) {
423 return; //anonymous players cannot be challenged
424 this.newchallenge.to = player.name;
425 doClick("modalNewgame");
427 newChallenge: async function() {
428 const vname = this.getVname(this.newchallenge.vid);
429 const vModule = await import("@/variants/" + vname + ".js");
430 window.V = vModule.VariantRules;
431 const error = checkChallenge(this.newchallenge);
434 const ctype = this.classifyObject(this.newchallenge);
435 if (ctype == "corr" && this.st.user.id <= 0)
436 return alert("Please log in to play correspondance games");
437 // NOTE: "from" information is not required here
438 let chall = Object.assign({}, this.newchallenge);
439 const finishAddChallenge = (cid,warnDisconnected) => {
440 chall.id = cid || "c" + getRandString();
441 // Send challenge to peers (if connected)
442 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
443 chall.added = Date.now();
444 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
447 chall.from = this.people[0]; //avoid sending email
448 this.challenges.push(chall);
449 localStorage.setItem("challenge", JSON.stringify(chall));
450 document.getElementById("modalNewgame").checked = false;
452 const cIdx = this.challenges.findIndex(
453 c => c.from.sid == this.st.user.sid && c.type == ctype);
456 // Delete current challenge (will be replaced now)
457 this.sendSomethingTo(this.challenges[cIdx].to,
458 "deletechallenge", {cid:this.challenges[cIdx].id});
464 {id: this.challenges[cIdx].id}
467 this.challenges.splice(cIdx, 1);
471 // Live challenges have a random ID
472 finishAddChallenge(null, "warnDisconnected");
476 // Correspondance game: send challenge to server
481 response => { finishAddChallenge(response.cid); }
485 clickChallenge: function(c) {
486 // In all cases, the challenge is consumed:
487 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
488 // NOTE: deletechallenge event might be redundant (but it's easier this way)
489 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
490 const myChallenge = (c.from.sid == this.st.user.sid //live
491 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
495 if (!!c.to) //c.to == this.st.user.name (connected)
497 // TODO: if special FEN, show diagram after loading variant
498 c.accepted = confirm("Accept challenge?");
502 c.seat = this.people[0]; //avoid sending email
507 this.st.conn.send(JSON.stringify({
508 code: "refusechallenge",
509 cid: c.id, target: c.from.sid}));
514 localStorage.removeItem("challenge");
515 if (c.type == "corr")
525 // NOTE: when launching game, the challenge is already deleted
526 launchGame: async function(c) {
527 const vModule = await import("@/variants/" + c.vname + ".js");
528 window.V = vModule.VariantRules;
529 // These game informations will be sent to other players
532 gameId: getRandString(),
533 fen: c.fen || V.GenRandInitFen(),
534 players: shuffle([c.from, c.seat]), //white then black
536 timeControl: c.timeControl,
538 this.st.conn.send(JSON.stringify({code:"newgame",
539 gameInfo:gameInfo, target:c.from.sid, cid:c.id}));
540 if (c.type == "live")
541 this.startNewGame(gameInfo);
542 else //corr: game only on server
547 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
548 response => { this.$router.push("/game/" + response.gameId); }
552 // NOTE: for live games only (corr games start on the server)
553 startNewGame: function(gameInfo) {
554 const game = Object.assign({}, gameInfo, {
555 // (other) Game infos: constant
556 fenStart: gameInfo.fen,
557 // Game state (including FEN): will be updated
559 clocks: [-1, -1], //-1 = unstarted
560 initime: [0, 0], //initialized later
563 GameStorage.add(game);
564 if (this.st.settings.sound >= 1)
565 new Audio("/sounds/newgame.mp3").play().catch(err => {});
566 this.$router.push("/game/" + gameInfo.gameId);