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 });
153 this.challenges = this.challenges.concat(
154 response.challenges.map(c => {
155 // (just players names in fact)
156 const from = {name: names[c.uid], id: c.uid};
157 const type = this.classifyObject(c);
158 const vname = this.getVname(c.vid);
159 return Object.assign({}, c, {type: type, vname: vname, from: from});
167 // 0.1] Ask server for room composition:
168 const funcPollClients = () => {
169 this.st.conn.send(JSON.stringify({code:"pollclients"}));
171 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
173 else //socket not ready yet (initial loading)
174 this.st.conn.onopen = funcPollClients;
175 this.st.conn.onmessage = this.socketMessageListener;
176 const socketCloseListener = () => {
177 store.socketCloseListener(); //reinitialize connexion (in store.js)
178 this.st.conn.addEventListener('message', this.socketMessageListener);
179 this.st.conn.addEventListener('close', socketCloseListener);
181 this.st.conn.onclose = socketCloseListener;
185 filterChallenges: function(type) {
186 return this.challenges.filter(c => c.type == type);
188 filterGames: function(type) {
189 return this.games.filter(g => g.type == type);
191 classifyObject: function(o) { //challenge or game
192 // Heuristic: should work for most cases... (TODO)
193 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
195 showGame: function(g) {
196 // NOTE: we are an observer, since only games I don't play are shown here
197 // ==> Moves sent by connected remote player(s) if live game
198 let url = "/game/" + g.id;
199 if (g.type == "live")
201 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
202 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
203 url += "?rid=" + remotes[rIdx].sid;
205 this.$router.push(url);
207 // TODO: ...filter(...)[0].name, one-line, just remove this function
208 getVname: function(vid) {
209 const vIdx = this.st.variants.findIndex(v => v.id == vid);
210 return this.st.variants[vIdx].name;
212 getSid: function(pname) {
213 const pIdx = this.people.findIndex(pl => pl.name == pname);
214 return (pIdx === -1 ? null : this.people[pIdx].sid);
216 getPname: function(sid) {
217 const pIdx = this.people.findIndex(pl => pl.sid == sid);
218 return (pIdx === -1 ? null : this.people[pIdx].name);
220 sendSomethingTo: function(to, code, obj, warnDisconnected) {
221 const doSend = (code, obj, sid) => {
222 this.st.conn.send(JSON.stringify(Object.assign(
231 // Challenge with targeted players
232 const targetSid = this.getSid(to);
235 if (!!warnDisconnected)
236 alert("Warning: " + pname + " is not connected");
239 doSend(code, obj, targetSid);
243 // Open challenge: send to all connected players (except us)
244 this.people.forEach(p => {
245 if (p.sid != this.st.user.sid) //only sid is always set
246 doSend(code, obj, p.sid);
251 socketMessageListener: function(msg) {
252 const data = JSON.parse(msg.data);
255 // 0.2] Receive clients list (just socket IDs)
258 data.sockIds.forEach(sid => {
259 this.people.push({sid:sid, id:0, name:""});
260 // Ask identity, challenges and game(s)
261 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
262 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
263 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
269 // Request for identification: reply if I'm not anonymous
270 if (this.st.user.id > 0)
272 this.st.conn.send(JSON.stringify(
273 // people[0] instead of st.user to avoid sending email
274 {code:"identity", user:this.people[0], target:data.from}));
280 // Send my current live challenge (if any)
281 const cIdx = this.challenges
282 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
285 const c = this.challenges[cIdx];
288 // Minimal challenge informations: (from not required)
293 timeControl: c.timeControl
295 this.st.conn.send(JSON.stringify({code:"challenge",
296 chall:myChallenge, target:data.from}));
302 // Send my current live game (if any)
303 GameStorage.getCurrent((game) => {
308 // Minimal game informations:
310 players: game.players.map(p => p.name),
312 timeControl: game.timeControl,
314 this.st.conn.send(JSON.stringify({code:"game",
315 game:myGame, target:data.from}));
322 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
323 this.people[pIdx].id = data.user.id;
324 this.people[pIdx].name = data.user.name;
329 // Receive challenge from some player (+sid)
330 let newChall = data.chall;
331 newChall.type = this.classifyObject(data.chall);
332 const pIdx = this.people.findIndex(p => p.sid == data.from);
333 newChall.from = this.people[pIdx]; //may be anonymous
334 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
335 newChall.vname = this.getVname(newChall.vid);
336 this.challenges.push(newChall);
341 // Receive game from some player (+sid)
342 // NOTE: it may be correspondance (if newgame while we are connected)
343 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
345 let newGame = data.game;
346 newGame.type = this.classifyObject(data.game);
347 newGame.vname = this.getVname(data.game.vid);
348 newGame.rid = data.from;
350 this.games.push(newGame);
356 // TODO: next line required ?!
357 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
358 // New game just started: data contain all information
359 if (this.classifyObject(data.gameInfo) == "live")
360 this.startNewGame(data.gameInfo);
363 // TODO: notify with game link but do not redirect
367 case "refusechallenge":
369 alert(this.getPname(data.from) + " declined your challenge");
370 ArrayFun.remove(this.challenges, c => c.id == data.cid);
373 case "deletechallenge":
375 // NOTE: the challenge may be already removed
376 ArrayFun.remove(this.challenges, c => c.id == data.cid);
377 localStorage.removeItem("challenge"); //in case of
382 this.people.push({name:"", id:0, sid:data.sid});
383 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
384 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
385 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
390 ArrayFun.remove(this.people, p => p.sid == data.sid);
391 // Also remove all challenges sent by this player:
392 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
393 // And all live games where he plays and no other opponent is online
394 ArrayFun.remove(this.games, g =>
395 g.type == "live" && (g.players.every(p => p.sid == data.sid
396 || !this.people.some(pl => pl.sid == p.sid))), "all");
401 // Challenge lifecycle:
402 tryChallenge: function(player) {
404 return; //anonymous players cannot be challenged
405 this.newchallenge.to = player.name;
406 doClick("modalNewgame");
408 newChallenge: async function() {
409 const vname = this.getVname(this.newchallenge.vid);
410 const vModule = await import("@/variants/" + vname + ".js");
411 window.V = vModule.VariantRules;
412 const error = checkChallenge(this.newchallenge);
415 const ctype = this.classifyObject(this.newchallenge);
416 if (ctype == "corr" && this.st.user.id <= 0)
417 return alert("Please log in to play correspondance games");
418 // NOTE: "from" information is not required here
419 let chall = Object.assign({}, this.newchallenge);
420 const finishAddChallenge = (cid,warnDisconnected) => {
421 chall.id = cid || "c" + getRandString();
422 // Send challenge to peers (if connected)
423 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
424 chall.added = Date.now();
425 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
428 chall.from = this.people[0]; //avoid sending email
429 this.challenges.push(chall);
430 localStorage.setItem("challenge", JSON.stringify(chall));
431 document.getElementById("modalNewgame").checked = false;
433 const cIdx = this.challenges.findIndex(
434 c => c.from.sid == this.st.user.sid && c.type == ctype);
437 // Delete current challenge (will be replaced now)
438 this.sendSomethingTo(this.challenges[cIdx].to,
439 "deletechallenge", {cid:this.challenges[cIdx].id});
445 {id: this.challenges[cIdx].id}
448 this.challenges.splice(cIdx, 1);
452 // Live challenges have a random ID
453 finishAddChallenge(null, "warnDisconnected");
457 // Correspondance game: send challenge to server
462 response => { finishAddChallenge(response.cid); }
466 clickChallenge: function(c) {
467 // In all cases, the challenge is consumed:
468 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
469 // NOTE: deletechallenge event might be redundant (but it's easier this way)
470 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
471 const myChallenge = (c.from.sid == this.st.user.sid //live
472 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
476 if (!!c.to) //c.to == this.st.user.name (connected)
478 // TODO: if special FEN, show diagram after loading variant
479 c.accepted = confirm("Accept challenge?");
483 c.seat = this.people[0]; //avoid sending email
488 this.st.conn.send(JSON.stringify({
489 code: "refusechallenge",
490 cid: c.id, target: c.from.sid}));
494 localStorage.removeItem("challenge");
495 if (c.type == "corr")
504 // NOTE: when launching game, the challenge is already deleted
505 launchGame: async function(c) {
506 const vModule = await import("@/variants/" + c.vname + ".js");
507 window.V = vModule.VariantRules;
508 // These game informations will be sent to other players
511 gameId: getRandString(),
512 fen: c.fen || V.GenRandInitFen(),
513 players: shuffle([c.from, c.seat]), //white then black
515 timeControl: c.timeControl,
517 this.st.conn.send(JSON.stringify({code:"newgame",
518 gameInfo:gameInfo, target:c.from.sid, cid:c.id}));
519 if (c.type == "live")
520 this.startNewGame(gameInfo);
521 else //corr: game only on server
528 // TODO: redirection here
531 // NOTE: for live games only (corr games start on the server)
532 startNewGame: function(gameInfo) {
533 const game = Object.assign({}, gameInfo, {
534 // (other) Game infos: constant
535 fenStart: gameInfo.fen,
536 // Game state (including FEN): will be updated
538 clocks: [-1, -1], //-1 = unstarted
539 initime: [0, 0], //initialized later
542 GameStorage.add(game);
543 if (this.st.settings.sound >= 1)
544 new Audio("/sounds/newgame.mp3").play().catch(err => {});
545 this.$router.push("/game/" + gameInfo.gameId);