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 oldOnclose = this.st.conn.onclose;
158 const socketCloseListener = () => {
159 oldOnclose(); //reinitialize connexion (in store.js)
160 this.st.conn.addEventListener('message', this.socketMessageListener);
161 this.st.conn.addEventListener('close', socketCloseListener);
163 this.st.conn.onclose = socketCloseListener;
167 filterChallenges: function(type) {
168 return this.challenges.filter(c => c.type == type);
170 filterGames: function(type) {
171 return this.games.filter(c => c.type == type);
173 classifyObject: function(o) { //challenge or game
174 // Heuristic: should work for most cases... (TODO)
175 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
177 showGame: function(g) {
178 // NOTE: we are an observer, since only games I don't play are shown here
179 // ==> Moves sent by connected remote player(s) if live game
180 let url = "/game/" + g.id;
181 if (g.type == "live")
183 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
184 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
185 url += "?rid=" + remotes[rIdx].sid;
187 this.$router.push(url);
189 getVname: function(vid) {
190 const vIdx = this.st.variants.findIndex(v => v.id == vid);
191 return this.st.variants[vIdx].name;
193 getSid: function(pname) {
194 const pIdx = this.people.findIndex(pl => pl.name == pname);
195 return (pIdx === -1 ? null : this.people[pIdx].sid);
197 getPname: function(sid) {
198 const pIdx = this.people.findIndex(pl => pl.sid == sid);
199 return (pIdx === -1 ? null : this.people[pIdx].name);
201 sendSomethingTo: function(to, code, obj, warnDisconnected) {
202 const doSend = (code, obj, sid) => {
203 this.st.conn.send(JSON.stringify(Object.assign(
212 // Challenge with targeted players
213 const targetSid = this.getSid(to);
216 if (!!warnDisconnected)
217 alert("Warning: " + pname + " is not connected");
220 doSend(code, obj, targetSid);
224 // Open challenge: send to all connected players (except us)
225 this.people.forEach(p => {
226 if (p.sid != this.st.user.sid) //only sid is always set
227 doSend(code, obj, p.sid);
232 socketMessageListener: function(msg) {
233 const data = JSON.parse(msg.data);
236 // 0.2] Receive clients list (just socket IDs)
239 data.sockIds.forEach(sid => {
240 this.people.push({sid:sid, id:0, name:""});
241 // Ask identity, challenges and game(s)
242 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
243 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
244 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
250 // Request for identification: reply if I'm not anonymous
251 if (this.st.user.id > 0)
253 this.st.conn.send(JSON.stringify(
254 {code:"identity", user:this.st.user, target:data.from}));
260 // Send my current live challenge (if any)
261 const cIdx = this.challenges
262 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
265 const c = this.challenges[cIdx];
268 // Minimal challenge informations: (from not required)
273 timeControl: c.timeControl
275 this.st.conn.send(JSON.stringify({code:"challenge",
276 chall:myChallenge, target:data.from}));
282 // Send my current live game (if any)
283 GameStorage.getCurrent((game) => {
288 // Minimal game informations:
290 players: game.players.map(p => p.name),
292 timeControl: game.timeControl,
294 this.st.conn.send(JSON.stringify({code:"game",
295 game:myGame, target:data.from}));
302 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
303 this.people[pIdx].id = data.user.id;
304 this.people[pIdx].name = data.user.name;
309 // Receive challenge from some player (+sid)
310 let newChall = data.chall;
311 newChall.type = this.classifyObject(data.chall);
312 const pIdx = this.people.findIndex(p => p.sid == data.from);
313 newChall.from = this.people[pIdx]; //may be anonymous
314 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
315 newChall.vname = this.getVname(newChall.vid); //TODO: just send vname?
316 this.challenges.push(newChall);
321 // Receive game from some player (+sid)
322 // NOTE: it may be correspondance (if newgame while we are connected)
323 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
325 let newGame = data.game;
326 newGame.type = this.classifyObject(data.game);
327 newGame.rid = data.from;
329 this.games.push(newGame);
335 // New game just started: data contain all informations
336 this.startNewGame(data.gameInfo);
337 // TODO: if live, redirect to game
338 // if corr, notify with link but do not redirect
341 case "refusechallenge":
343 alert(this.getPname(data.from) + " declined your challenge");
344 ArrayFun.remove(this.challenges, c => c.id == data.cid);
347 case "deletechallenge":
349 // NOTE: the challenge may be already removed
350 ArrayFun.remove(this.challenges, c => c.id == data.cid);
355 this.people.push({name:"", id:0, sid:data.sid});
356 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
357 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
358 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
363 ArrayFun.remove(this.people, p => p.sid == data.sid);
364 // Also remove all challenges sent by this player:
365 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
366 // And all live games where he plays and no other opponent is online
367 ArrayFun.remove(this.games, g =>
368 g.type == "live" && (g.players.every(p => p.sid == data.sid
369 || !this.people.some(pl => pl.sid == p.sid))), "all");
374 // Challenge lifecycle:
375 tryChallenge: function(player) {
377 return; //anonymous players cannot be challenged
378 this.newchallenge.to[0] = player.name;
379 doClick("modalNewgame");
381 newChallenge: async function() {
382 const vname = this.getVname(this.newchallenge.vid);
383 const vModule = await import("@/variants/" + vname + ".js");
384 window.V = vModule.VariantRules;
385 const error = checkChallenge(this.newchallenge);
388 const ctype = this.classifyObject(this.newchallenge);
389 // NOTE: "from" information is not required here
392 fen: this.newchallenge.fen,
393 to: this.newchallenge.to,
394 timeControl: this.newchallenge.timeControl,
395 vid: this.newchallenge.vid,
397 const finishAddChallenge = (cid,warnDisconnected) => {
398 chall.id = cid || "c" + getRandString();
399 // Send challenge to peers (if connected)
400 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
401 chall.added = Date.now();
404 chall.from = this.st.user;
405 this.challenges.push(chall);
406 localStorage.setItem("challenge", JSON.stringify(chall));
407 document.getElementById("modalNewgame").checked = false;
409 const cIdx = this.challenges.findIndex(
410 c => c.from.sid == this.st.user.sid && c.type == ctype);
413 // Delete current challenge (will be replaced now)
414 this.sendSomethingTo(this.challenges[cIdx].to,
415 "deletechallenge", {cid:this.challenges[cIdx].id});
421 {id: this.challenges[cIdx].id}
424 this.challenges.splice(cIdx, 1);
428 // Live challenges have a random ID
429 finishAddChallenge(null, "warnDisconnected");
433 // Correspondance game: send challenge to server
438 response => { finishAddChallenge(response.cid); }
442 clickChallenge: function(c) {
443 const myChallenge = (c.from.sid == this.st.user.sid //live
444 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
448 if (!!c.to) //c.to == this.st.user.name (connected)
450 // TODO: if special FEN, show diagram after loading variant
451 c.accepted = confirm("Accept challenge?");
455 c.seat = this.st.user;
460 this.st.conn.send(JSON.stringify({
461 code: "refusechallenge",
462 cid: c.id, target: c.from.sid}));
466 localStorage.removeItem("challenge");
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, "deletechallenge", {cid:c.id});
471 if (c.type == "corr")
476 {id: this.challenges[cIdx].id}
480 // NOTE: when launching game, the challenge is already deleted
481 launchGame: async function(c) {
482 const vname = this.getVname(c.vid);
483 const vModule = await import("@/variants/" + vname + ".js");
484 window.V = vModule.VariantRules;
485 let players = [c.from, c.seat];
486 // These game informations will be sent to other players
489 gameId: getRandString(),
490 fen: c.fen || V.GenRandInitFen(),
491 // Players' names may be required if game start when a player is offline
492 // Shuffle players order (white then black).
493 players: shuffle(players.map(p => { return {name:p.name, sid:p.sid} })),
495 timeControl: c.timeControl,
497 this.st.conn.send(JSON.stringify({code:"newgame",
498 gameInfo:gameInfo, target:c.seat.sid}));
499 if (c.type == "live")
500 this.startNewGame(gameInfo);
501 else //corr: game only on server
510 // NOTE: for live games only (corr games are launched on server)
511 startNewGame: function(gameInfo) {
512 // Extract times (in [milli]seconds), set clocks
513 const tc = extractTime(gameInfo.timeControl);
514 let initime = [...Array(gameInfo.players.length)];
515 initime[0] = Date.now();
518 // Game infos: constant
519 gameId: gameInfo.gameId,
520 vname: this.getVname(gameInfo.vid),
521 fenStart: gameInfo.fen,
522 players: gameInfo.players,
523 timeControl: gameInfo.timeControl,
524 increment: tc.increment,
525 mode: "live", //function for live games only
526 // Game state: will be updated
529 clocks: [...Array(gameInfo.players.length)].fill(tc.mainTime),
533 GameStorage.add(game);
534 if (this.st.settings.sound >= 1)
535 new Audio("/sounds/newgame.mp3").play().catch(err => {});
536 // TODO: redirect to game