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";
73 import { extractTime } from "@/utils/timeControl";
83 cdisplay: "live", //or corr
84 pdisplay: "players", //or chat
88 people: [], //(all) online players
92 to: "", //name of challenged player (if any)
93 timeControl: "", //"2m+2s" ...etc
98 uniquePlayers: function() {
99 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
100 let anonymous = {id:0, name:"@nonymous", count:0};
102 this.people.forEach(p => {
108 if (anonymous.count > 0)
109 playerList.push(anonymous);
113 created: function() {
114 // Always add myself to players' list
115 this.people.push(this.st.user);
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 console.log(response.challenges);
147 // TODO: post-treatment on challenges ?
148 Array.prototype.push.apply(this.challenges, response.challenges);
152 // 0.1] Ask server for room composition:
153 const funcPollClients = () => {
154 this.st.conn.send(JSON.stringify({code:"pollclients"}));
156 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
158 else //socket not ready yet (initial loading)
159 this.st.conn.onopen = funcPollClients;
160 this.st.conn.onmessage = this.socketMessageListener;
161 const socketCloseListener = () => {
162 store.socketCloseListener(); //reinitialize connexion (in store.js)
163 this.st.conn.addEventListener('message', this.socketMessageListener);
164 this.st.conn.addEventListener('close', socketCloseListener);
166 this.st.conn.onclose = socketCloseListener;
170 filterChallenges: function(type) {
171 return this.challenges.filter(c => c.type == type);
173 filterGames: function(type) {
174 return this.games.filter(g => g.type == type);
176 classifyObject: function(o) { //challenge or game
177 // Heuristic: should work for most cases... (TODO)
178 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
180 showGame: function(g) {
181 // NOTE: we are an observer, since only games I don't play are shown here
182 // ==> Moves sent by connected remote player(s) if live game
183 let url = "/game/" + g.id;
184 if (g.type == "live")
186 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
187 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
188 url += "?rid=" + remotes[rIdx].sid;
190 this.$router.push(url);
192 // TODO: ...filter(...)[0].name, one-line, just remove this function
193 getVname: function(vid) {
194 const vIdx = this.st.variants.findIndex(v => v.id == vid);
195 return this.st.variants[vIdx].name;
197 getSid: function(pname) {
198 const pIdx = this.people.findIndex(pl => pl.name == pname);
199 return (pIdx === -1 ? null : this.people[pIdx].sid);
201 getPname: function(sid) {
202 const pIdx = this.people.findIndex(pl => pl.sid == sid);
203 return (pIdx === -1 ? null : this.people[pIdx].name);
205 sendSomethingTo: function(to, code, obj, warnDisconnected) {
206 const doSend = (code, obj, sid) => {
207 this.st.conn.send(JSON.stringify(Object.assign(
216 // Challenge with targeted players
217 const targetSid = this.getSid(to);
220 if (!!warnDisconnected)
221 alert("Warning: " + pname + " is not connected");
224 doSend(code, obj, targetSid);
228 // Open challenge: send to all connected players (except us)
229 this.people.forEach(p => {
230 if (p.sid != this.st.user.sid) //only sid is always set
231 doSend(code, obj, p.sid);
236 socketMessageListener: function(msg) {
237 const data = JSON.parse(msg.data);
240 // 0.2] Receive clients list (just socket IDs)
243 data.sockIds.forEach(sid => {
244 this.people.push({sid:sid, id:0, name:""});
245 // Ask identity, challenges and game(s)
246 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
247 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
248 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
254 // Request for identification: reply if I'm not anonymous
255 if (this.st.user.id > 0)
257 this.st.conn.send(JSON.stringify(
258 {code:"identity", user:this.st.user, target:data.from}));
264 // Send my current live challenge (if any)
265 const cIdx = this.challenges
266 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
269 const c = this.challenges[cIdx];
272 // Minimal challenge informations: (from not required)
277 timeControl: c.timeControl
279 this.st.conn.send(JSON.stringify({code:"challenge",
280 chall:myChallenge, target:data.from}));
286 // Send my current live game (if any)
287 GameStorage.getCurrent((game) => {
292 // Minimal game informations:
294 players: game.players.map(p => p.name),
296 timeControl: game.timeControl,
298 this.st.conn.send(JSON.stringify({code:"game",
299 game:myGame, target:data.from}));
306 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
307 this.people[pIdx].id = data.user.id;
308 this.people[pIdx].name = data.user.name;
313 // Receive challenge from some player (+sid)
314 let newChall = data.chall;
315 newChall.type = this.classifyObject(data.chall);
316 const pIdx = this.people.findIndex(p => p.sid == data.from);
317 newChall.from = this.people[pIdx]; //may be anonymous
318 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
319 newChall.vname = this.getVname(newChall.vid);
320 this.challenges.push(newChall);
325 // Receive game from some player (+sid)
326 // NOTE: it may be correspondance (if newgame while we are connected)
327 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
329 let newGame = data.game;
330 newGame.type = this.classifyObject(data.game);
331 newGame.vname = this.getVname(data.game.vid);
332 newGame.rid = data.from;
334 this.games.push(newGame);
340 // New game just started: data contain all information
341 if (data.gameInfo.type == "live")
342 this.startNewGame(data.gameInfo);
345 // TODO: notify with game link but do not redirect
349 case "refusechallenge":
351 alert(this.getPname(data.from) + " declined your challenge");
352 ArrayFun.remove(this.challenges, c => c.id == data.cid);
355 case "deletechallenge":
357 // NOTE: the challenge may be already removed
358 ArrayFun.remove(this.challenges, c => c.id == data.cid);
363 this.people.push({name:"", id:0, sid:data.sid});
364 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
365 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
366 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
371 ArrayFun.remove(this.people, p => p.sid == data.sid);
372 // Also remove all challenges sent by this player:
373 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
374 // And all live games where he plays and no other opponent is online
375 ArrayFun.remove(this.games, g =>
376 g.type == "live" && (g.players.every(p => p.sid == data.sid
377 || !this.people.some(pl => pl.sid == p.sid))), "all");
382 // Challenge lifecycle:
383 tryChallenge: function(player) {
385 return; //anonymous players cannot be challenged
386 this.newchallenge.to = player.name;
387 doClick("modalNewgame");
389 newChallenge: async function() {
390 const vname = this.getVname(this.newchallenge.vid);
391 const vModule = await import("@/variants/" + vname + ".js");
392 window.V = vModule.VariantRules;
393 const error = checkChallenge(this.newchallenge);
396 const ctype = this.classifyObject(this.newchallenge);
397 // NOTE: "from" information is not required here
398 let chall = Object.assign({}, this.newchallenge);
399 const finishAddChallenge = (cid,warnDisconnected) => {
400 chall.id = cid || "c" + getRandString();
401 // Send challenge to peers (if connected)
402 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
403 chall.added = Date.now();
404 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
407 chall.from = this.st.user;
408 this.challenges.push(chall);
409 localStorage.setItem("challenge", JSON.stringify(chall));
410 document.getElementById("modalNewgame").checked = false;
412 const cIdx = this.challenges.findIndex(
413 c => c.from.sid == this.st.user.sid && c.type == ctype);
416 // Delete current challenge (will be replaced now)
417 this.sendSomethingTo(this.challenges[cIdx].to,
418 "deletechallenge", {cid:this.challenges[cIdx].id});
424 {id: this.challenges[cIdx].id}
427 this.challenges.splice(cIdx, 1);
431 // Live challenges have a random ID
432 finishAddChallenge(null, "warnDisconnected");
436 // Correspondance game: send challenge to server
441 response => { finishAddChallenge(response.cid); }
445 clickChallenge: function(c) {
446 const myChallenge = (c.from.sid == this.st.user.sid //live
447 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
451 if (!!c.to) //c.to == this.st.user.name (connected)
453 // TODO: if special FEN, show diagram after loading variant
454 c.accepted = confirm("Accept challenge?");
458 c.seat = this.st.user;
463 this.st.conn.send(JSON.stringify({
464 code: "refusechallenge",
465 cid: c.id, target: c.from.sid}));
469 localStorage.removeItem("challenge");
470 // In all cases, the challenge is consumed:
471 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
472 // NOTE: deletechallenge event might be redundant (but it's easier this way)
473 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
474 if (c.type == "corr")
479 {id: this.challenges[cIdx].id}
483 // NOTE: when launching game, the challenge is already deleted
484 launchGame: async function(c) {
485 const vModule = await import("@/variants/" + c.vname + ".js");
486 window.V = vModule.VariantRules;
487 // These game informations will be sent to other players
490 gameId: getRandString(),
491 fen: c.fen || V.GenRandInitFen(),
492 players: shuffle([c.from, c.seat]), //white then black
494 timeControl: c.timeControl,
496 this.st.conn.send(JSON.stringify({code:"newgame",
497 gameInfo:gameInfo, target:c.seat.sid}));
498 if (c.type == "live")
499 this.startNewGame(gameInfo);
500 else //corr: game only on server
509 // NOTE: for live games only (corr games start on the server)
510 startNewGame: function(gameInfo) {
511 const game = Object.assign({}, gameInfo, {
512 // (other) Game infos: constant
513 fenStart: gameInfo.fen,
514 // Game state (including FEN): will be updated
516 clocks: [-1, -1], //-1 = unstarted
517 initime: [0, 0], //timer starts after first 2 half-moves
520 GameStorage.add(game);
521 if (this.st.settings.sound >= 1)
522 new Audio("/sounds/newgame.mp3").play().catch(err => {});
523 // TODO: redirect to game