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 // {excluded: this.st.user.id},
133 // this.games = this.games.concat(response.games);
136 // Also ask for corr challenges (open + sent to me)
140 {uid: this.st.user.id},
142 console.log(response.challenges);
143 // TODO: post-treatment on challenges ?
144 Array.prototype.push.apply(this.challenges, response.challenges);
148 // 0.1] Ask server for room composition:
149 const funcPollClients = () => {
150 this.st.conn.send(JSON.stringify({code:"pollclients"}));
152 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
154 else //socket not ready yet (initial loading)
155 this.st.conn.onopen = funcPollClients;
156 this.st.conn.onmessage = this.socketMessageListener;
157 const socketCloseListener = () => {
158 store.socketCloseListener(); //reinitialize connexion (in store.js)
159 this.st.conn.addEventListener('message', this.socketMessageListener);
160 this.st.conn.addEventListener('close', socketCloseListener);
162 this.st.conn.onclose = socketCloseListener;
166 filterChallenges: function(type) {
167 return this.challenges.filter(c => c.type == type);
169 filterGames: function(type) {
170 return this.games.filter(c => c.type == type);
172 classifyObject: function(o) { //challenge or game
173 // Heuristic: should work for most cases... (TODO)
174 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
176 showGame: function(g) {
177 // NOTE: we are an observer, since only games I don't play are shown here
178 // ==> Moves sent by connected remote player(s) if live game
179 let url = "/game/" + g.id;
180 if (g.type == "live")
182 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
183 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
184 url += "?rid=" + remotes[rIdx].sid;
186 this.$router.push(url);
188 getVname: function(vid) {
189 const vIdx = this.st.variants.findIndex(v => v.id == vid);
190 return this.st.variants[vIdx].name;
192 getSid: function(pname) {
193 const pIdx = this.people.findIndex(pl => pl.name == pname);
194 return (pIdx === -1 ? null : this.people[pIdx].sid);
196 getPname: function(sid) {
197 const pIdx = this.people.findIndex(pl => pl.sid == sid);
198 return (pIdx === -1 ? null : this.people[pIdx].name);
200 sendSomethingTo: function(to, code, obj, warnDisconnected) {
201 const doSend = (code, obj, sid) => {
202 this.st.conn.send(JSON.stringify(Object.assign(
211 // Challenge with targeted players
212 const targetSid = this.getSid(to);
215 if (!!warnDisconnected)
216 alert("Warning: " + pname + " is not connected");
219 doSend(code, obj, targetSid);
223 // Open challenge: send to all connected players (except us)
224 this.people.forEach(p => {
225 if (p.sid != this.st.user.sid) //only sid is always set
226 doSend(code, obj, p.sid);
231 socketMessageListener: function(msg) {
232 const data = JSON.parse(msg.data);
235 // 0.2] Receive clients list (just socket IDs)
238 data.sockIds.forEach(sid => {
239 this.people.push({sid:sid, id:0, name:""});
240 // Ask identity, challenges and game(s)
241 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
242 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
243 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
249 // Request for identification: reply if I'm not anonymous
250 if (this.st.user.id > 0)
252 this.st.conn.send(JSON.stringify(
253 {code:"identity", user:this.st.user, target:data.from}));
259 // Send my current live challenge (if any)
260 const cIdx = this.challenges
261 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
264 const c = this.challenges[cIdx];
267 // Minimal challenge informations: (from not required)
272 timeControl: c.timeControl
274 this.st.conn.send(JSON.stringify({code:"challenge",
275 chall:myChallenge, target:data.from}));
281 // Send my current live game (if any)
282 GameStorage.getCurrent((game) => {
287 // Minimal game informations:
289 players: game.players.map(p => p.name),
291 timeControl: game.timeControl,
293 this.st.conn.send(JSON.stringify({code:"game",
294 game:myGame, target:data.from}));
301 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
302 this.people[pIdx].id = data.user.id;
303 this.people[pIdx].name = data.user.name;
308 // Receive challenge from some player (+sid)
309 let newChall = data.chall;
310 newChall.type = this.classifyObject(data.chall);
311 const pIdx = this.people.findIndex(p => p.sid == data.from);
312 newChall.from = this.people[pIdx]; //may be anonymous
313 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
314 newChall.vname = this.getVname(newChall.vid); //TODO: just send vname?
315 this.challenges.push(newChall);
320 // Receive game from some player (+sid)
321 // NOTE: it may be correspondance (if newgame while we are connected)
322 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
324 let newGame = data.game;
325 newGame.type = this.classifyObject(data.game);
326 newGame.rid = data.from;
328 this.games.push(newGame);
334 // New game just started: data contain all informations
335 this.startNewGame(data.gameInfo);
336 // TODO: if live, redirect to game
337 // if corr, notify with link but do not redirect
340 case "refusechallenge":
342 alert(this.getPname(data.from) + " declined your challenge");
343 ArrayFun.remove(this.challenges, c => c.id == data.cid);
346 case "deletechallenge":
348 // NOTE: the challenge may be already removed
349 ArrayFun.remove(this.challenges, c => c.id == data.cid);
354 this.people.push({name:"", id:0, sid:data.sid});
355 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
356 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
357 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
362 ArrayFun.remove(this.people, p => p.sid == data.sid);
363 // Also remove all challenges sent by this player:
364 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
365 // And all live games where he plays and no other opponent is online
366 ArrayFun.remove(this.games, g =>
367 g.type == "live" && (g.players.every(p => p.sid == data.sid
368 || !this.people.some(pl => pl.sid == p.sid))), "all");
373 // Challenge lifecycle:
374 tryChallenge: function(player) {
376 return; //anonymous players cannot be challenged
377 this.newchallenge.to[0] = player.name;
378 doClick("modalNewgame");
380 newChallenge: async function() {
381 const vname = this.getVname(this.newchallenge.vid);
382 const vModule = await import("@/variants/" + vname + ".js");
383 window.V = vModule.VariantRules;
384 const error = checkChallenge(this.newchallenge);
387 const ctype = this.classifyObject(this.newchallenge);
388 // NOTE: "from" information is not required here
391 fen: this.newchallenge.fen,
392 to: this.newchallenge.to,
393 timeControl: this.newchallenge.timeControl,
394 vid: this.newchallenge.vid,
396 const finishAddChallenge = (cid,warnDisconnected) => {
397 chall.id = cid || "c" + getRandString();
398 // Send challenge to peers (if connected)
399 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
400 chall.added = Date.now();
403 chall.from = this.st.user;
404 this.challenges.push(chall);
405 localStorage.setItem("challenge", JSON.stringify(chall));
406 document.getElementById("modalNewgame").checked = false;
408 const cIdx = this.challenges.findIndex(
409 c => c.from.sid == this.st.user.sid && c.type == ctype);
412 // Delete current challenge (will be replaced now)
413 this.sendSomethingTo(this.challenges[cIdx].to,
414 "deletechallenge", {cid:this.challenges[cIdx].id});
420 {id: this.challenges[cIdx].id}
423 this.challenges.splice(cIdx, 1);
427 // Live challenges have a random ID
428 finishAddChallenge(null, "warnDisconnected");
432 // Correspondance game: send challenge to server
437 response => { finishAddChallenge(response.cid); }
441 clickChallenge: function(c) {
442 const myChallenge = (c.from.sid == this.st.user.sid //live
443 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
447 if (!!c.to) //c.to == this.st.user.name (connected)
449 // TODO: if special FEN, show diagram after loading variant
450 c.accepted = confirm("Accept challenge?");
454 c.seat = this.st.user;
459 this.st.conn.send(JSON.stringify({
460 code: "refusechallenge",
461 cid: c.id, target: c.from.sid}));
465 localStorage.removeItem("challenge");
466 // In all cases, the challenge is consumed:
467 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
468 // NOTE: deletechallenge event might be redundant (but it's easier this way)
469 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
470 if (c.type == "corr")
475 {id: this.challenges[cIdx].id}
479 // NOTE: when launching game, the challenge is already deleted
480 launchGame: async function(c) {
481 const vname = this.getVname(c.vid);
482 const vModule = await import("@/variants/" + vname + ".js");
483 window.V = vModule.VariantRules;
484 let players = [c.from, c.seat];
485 // These game informations will be sent to other players
488 gameId: getRandString(),
489 fen: c.fen || V.GenRandInitFen(),
490 // Players' names may be required if game start when a player is offline
491 // Shuffle players order (white then black).
492 players: shuffle(players.map(p => { return {name:p.name, sid:p.sid} })),
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 are launched on server)
510 startNewGame: function(gameInfo) {
511 // Extract times (in [milli]seconds), set clocks
512 const tc = extractTime(gameInfo.timeControl);
513 let initime = [...Array(gameInfo.players.length)];
514 initime[0] = Date.now();
517 // Game infos: constant
518 gameId: gameInfo.gameId,
519 vname: this.getVname(gameInfo.vid),
520 fenStart: gameInfo.fen,
521 players: gameInfo.players,
522 timeControl: gameInfo.timeControl,
523 increment: tc.increment,
524 mode: "live", //function for live games only
525 // Game state: will be updated
528 clocks: [...Array(gameInfo.players.length)].fill(tc.mainTime),
532 GameStorage.add(game);
533 if (this.st.settings.sound >= 1)
534 new Audio("/sounds/newgame.mp3").play().catch(err => {});
535 // TODO: redirect to game