3 input#modalInfo.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="infoMessage")
5 .card.smallpad.small-modal.text-center
6 label.modal-close(for="modalInfo")
8 p(v-html="infoMessage")
9 input#modalNewgame.modal(type="checkbox")
10 div(role="dialog" aria-labelledby="titleFenedit")
11 .card.smallpad(@keyup.enter="newChallenge")
12 label#closeNewgame.modal-close(for="modalNewgame")
14 label(for="selectVariant") {{ st.tr["Variant"] }}
15 select#selectVariant(v-model="newchallenge.vid")
16 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
18 label(for="timeControl") {{ st.tr["Time control"] }}
19 input#timeControl(type="text" v-model="newchallenge.timeControl"
20 placeholder="3m+2s, 1h+30s, 7d+1d ...")
21 fieldset(v-if="st.user.id > 0")
22 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
23 input#selectPlayers(type="text" v-model="newchallenge.to")
24 fieldset(v-if="st.user.id > 0")
25 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
26 input#inputFen(type="text" v-model="newchallenge.fen")
27 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
29 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
30 button(onClick="doClick('modalNewgame')") New game
32 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
34 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
35 label(for="challengeSection" aria-hidden="true") Challenges
38 button(@click="cdisplay='live'") Live Challenges
39 button(@click="cdisplay='corr'") Correspondance challenges
40 ChallengeList(v-show="cdisplay=='live'"
41 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
42 ChallengeList(v-show="cdisplay=='corr'"
43 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
44 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
45 label(for="peopleSection" aria-hidden="true") People
48 button(@click="pdisplay='players'") Players
49 button(@click="pdisplay='chat'") Chat
50 #players(v-show="pdisplay=='players'")
52 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
53 :class="{anonymous: !!p.count}"
55 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
56 #chat(v-show="pdisplay=='chat'")
58 input#gameSection(type="radio" aria-hidden="true" name="accordion")
59 label(for="gameSection" aria-hidden="true") Games
62 button(@click="gdisplay='live'") Live games
63 button(@click="gdisplay='corr'") Correspondance games
64 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
65 @show-game="showGame")
66 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
67 @show-game="showGame")
71 import { store } from "@/store";
72 import { checkChallenge } from "@/data/challengeCheck";
73 import { ArrayFun } from "@/utils/array";
74 import { ajax } from "@/utils/ajax";
75 import { getRandString, shuffle } from "@/utils/alea";
76 import GameList from "@/components/GameList.vue";
77 import ChallengeList from "@/components/ChallengeList.vue";
78 import { GameStorage } from "@/utils/gameStorage";
88 cdisplay: "live", //or corr
89 pdisplay: "players", //or chat
93 people: [], //people in main hall
98 to: "", //name of challenged player (if any)
99 timeControl: "", //"2m+2s" ...etc
104 // st.variants changes only once, at loading from [] to [...]
105 "st.variants": function(variantArray) {
106 // Set potential challenges and games variant names:
107 this.challenges.forEach(c => {
109 c.vname = this.getVname(c.vid);
111 this.games.forEach(g => {
113 g.vname = this.getVname(g.vid);
118 uniquePlayers: function() {
119 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
120 let anonymous = {name:"@nonymous", count:0};
122 this.people.forEach(p => {
125 // We don't count registered users connections: either they are here or not.
126 if (!playerList[p.id])
127 playerList[p.id] = {name: p.name, count: 0};
132 if (anonymous.count > 0)
133 playerList[0] = anonymous;
134 return Object.values(playerList);
137 created: function() {
138 // Always add myself to players' list
139 const my = this.st.user;
140 this.people.push({sid:my.sid, id:my.id, name:my.name});
141 // Retrieve live challenge (not older than 30 minute) if any:
142 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
145 if ((Date.now() - chall.added)/1000 <= 30*60)
146 this.challenges.push(chall);
148 localStorage.removeItem("challenge");
150 // Ask server for current corr games (all but mines)
154 {uid: this.st.user.id, excluded: true},
156 this.games = this.games.concat(response.games.map(g => {
157 const type = this.classifyObject(g);
158 const vname = this.getVname(g.vid);
159 return Object.assign({}, g, {type: type, vname: vname});
163 // Also ask for corr challenges (open + sent to me)
167 {uid: this.st.user.id},
169 // Gather all senders names, and then retrieve full identity:
170 // (TODO [perf]: some might be online...)
171 const uids = response.challenges.map(c => { return c.uid });
174 { ids: uids.join(",") },
177 response2.users.forEach(u => {names[u.id] = u.name});
178 this.challenges = this.challenges.concat(
179 response.challenges.map(c => {
180 // (just players names in fact)
181 const from = {name: names[c.uid], id: c.uid};
182 const type = this.classifyObject(c);
183 const vname = this.getVname(c.vid);
184 return Object.assign({}, c, {type: type, vname: vname, from: from});
191 // 0.1] Ask server for room composition:
192 const funcPollClients = () => {
193 this.st.conn.send(JSON.stringify({code:"pollclients"}));
195 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
197 else //socket not ready yet (initial loading)
198 this.st.conn.onopen = funcPollClients;
199 this.st.conn.onmessage = this.socketMessageListener;
200 const socketCloseListener = () => {
201 store.socketCloseListener(); //reinitialize connexion (in store.js)
202 this.st.conn.addEventListener('message', this.socketMessageListener);
203 this.st.conn.addEventListener('close', socketCloseListener);
205 this.st.conn.onclose = socketCloseListener;
209 filterChallenges: function(type) {
210 return this.challenges.filter(c => c.type == type);
212 filterGames: function(type) {
213 return this.games.filter(g => g.type == type);
215 classifyObject: function(o) { //challenge or game
216 // Heuristic: should work for most cases... (TODO)
217 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
219 showGame: function(g) {
220 // NOTE: we are an observer, since only games I don't play are shown here
221 // ==> Moves sent by connected remote player(s) if live game
222 let url = "/game/" + g.id;
223 if (g.type == "live")
224 url += "?rid=" + g.rid;
225 this.$router.push(url);
227 getVname: function(vid) {
228 const variant = this.st.variants.find(v => v.id == vid);
229 // this.st.variants might be uninitialized (variant == null)
230 return (!!variant ? variant.name : "");
232 getSid: function(pname) {
233 const pIdx = this.people.findIndex(pl => pl.name == pname);
234 return (pIdx === -1 ? null : this.people[pIdx].sid);
236 getPname: function(sid) {
237 const pIdx = this.people.findIndex(pl => pl.sid == sid);
238 return (pIdx === -1 ? null : this.people[pIdx].name);
240 sendSomethingTo: function(to, code, obj, warnDisconnected) {
241 const doSend = (code, obj, sid) => {
242 this.st.conn.send(JSON.stringify(Object.assign(
251 // Challenge with targeted players
252 const targetSid = this.getSid(to);
255 if (!!warnDisconnected)
256 alert("Warning: " + pname + " is not connected");
259 doSend(code, obj, targetSid);
263 // Open challenge: send to all connected players (except us)
264 this.people.forEach(p => {
265 if (p.sid != this.st.user.sid) //only sid is always set
266 doSend(code, obj, p.sid);
271 socketMessageListener: function(msg) {
272 const data = JSON.parse(msg.data);
276 alert("Warning: duplicate 'offline' connection");
278 // 0.2] Receive clients list (just socket IDs)
281 data.sockIds.forEach(sid => {
282 this.people.push({sid:sid, id:0, name:""});
283 // Ask identity, challenges and game(s)
284 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
285 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
287 // Also ask current games to all playing peers (TODO: some design issue)
288 this.st.conn.send(JSON.stringify({code:"askgames"}));
293 // Request for identification: reply if I'm not anonymous
294 if (this.st.user.id > 0)
296 this.st.conn.send(JSON.stringify(
297 // people[0] instead of st.user to avoid sending email
298 {code:"identity", user:this.people[0], target:data.from}));
304 // Send my current live challenge (if any)
305 const cIdx = this.challenges
306 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
309 const c = this.challenges[cIdx];
312 // Minimal challenge informations: (from not required)
317 timeControl: c.timeControl
319 this.st.conn.send(JSON.stringify({code:"challenge",
320 chall:myChallenge, target:data.from}));
326 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
327 this.people[pIdx].id = data.user.id;
328 this.people[pIdx].name = data.user.name;
333 // Receive challenge from some player (+sid)
334 let newChall = data.chall;
335 newChall.type = this.classifyObject(data.chall);
336 const pIdx = this.people.findIndex(p => p.sid == data.from);
337 newChall.from = this.people[pIdx]; //may be anonymous
338 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
339 newChall.vname = this.getVname(newChall.vid);
340 this.challenges.push(newChall);
345 // Receive game from some player (+sid)
346 // NOTE: it may be correspondance (if newgame while we are connected)
347 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
349 let newGame = data.game;
350 newGame.type = this.classifyObject(data.game);
351 newGame.vname = this.getVname(data.game.vid);
352 newGame.rid = data.from;
354 this.games.push(newGame);
360 // TODO: next line required ?!
361 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
362 // New game just started: data contain all information
363 if (this.classifyObject(data.gameInfo) == "live")
364 this.startNewGame(data.gameInfo);
367 this.infoMessage = "New game started: " +
368 "<a href='#/game/" + data.gameInfo.id + "'>" +
369 "#/game/" + data.gameInfo.id + "</a>";
370 let modalBox = document.getElementById("modalInfo");
371 modalBox.checked = true;
372 setTimeout(() => { modalBox.checked = false; }, 3000);
376 case "refusechallenge":
378 alert(this.getPname(data.from) + " declined your challenge");
379 ArrayFun.remove(this.challenges, c => c.id == data.cid);
382 case "deletechallenge":
384 // NOTE: the challenge may be already removed
385 ArrayFun.remove(this.challenges, c => c.id == data.cid);
386 localStorage.removeItem("challenge"); //in case of
391 this.people.push({name:"", id:0, sid:data.from});
392 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
393 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
394 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
399 ArrayFun.remove(this.people, p => p.sid == data.from);
400 // Also remove all challenges sent by this player:
401 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
402 // And all live games where he plays and no other opponent is online
403 ArrayFun.remove(this.games, g =>
404 g.type == "live" && (g.players.every(p => p.sid == data.from
405 || !this.people.some(pl => pl.sid == p.sid))), "all");
410 // Challenge lifecycle:
411 tryChallenge: function(player) {
413 return; //anonymous players cannot be challenged
414 this.newchallenge.to = player.name;
415 doClick("modalNewgame");
417 newChallenge: async function() {
418 const vname = this.getVname(this.newchallenge.vid);
419 const vModule = await import("@/variants/" + vname + ".js");
420 window.V = vModule.VariantRules;
421 const error = checkChallenge(this.newchallenge);
424 const ctype = this.classifyObject(this.newchallenge);
425 if (ctype == "corr" && this.st.user.id <= 0)
426 return alert("Please log in to play correspondance games");
427 // NOTE: "from" information is not required here
428 let chall = Object.assign({}, this.newchallenge);
429 const finishAddChallenge = (cid,warnDisconnected) => {
430 chall.id = cid || "c" + getRandString();
431 // Send challenge to peers (if connected)
432 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
433 chall.added = Date.now();
434 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
437 chall.from = this.people[0]; //avoid sending email
438 this.challenges.push(chall);
440 localStorage.setItem("challenge", JSON.stringify(chall));
441 document.getElementById("modalNewgame").checked = false;
443 const cIdx = this.challenges.findIndex(
444 c => c.from.sid == this.st.user.sid && c.type == ctype);
447 // Delete current challenge (will be replaced now)
448 this.sendSomethingTo(this.challenges[cIdx].to,
449 "deletechallenge", {cid:this.challenges[cIdx].id});
455 {id: this.challenges[cIdx].id}
458 this.challenges.splice(cIdx, 1);
462 // Live challenges have a random ID
463 finishAddChallenge(null, "warnDisconnected");
467 // Correspondance game: send challenge to server
472 response => { finishAddChallenge(response.cid); }
476 clickChallenge: function(c) {
477 const myChallenge = (c.from.sid == this.st.user.sid //live
478 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
481 if (c.type == "corr" && this.st.user.id <= 0)
482 return alert("Please log in to accept corr challenges");
484 if (!!c.to) //c.to == this.st.user.name (connected)
486 // TODO: if special FEN, show diagram after loading variant
487 c.accepted = confirm("Accept challenge?");
491 c.seat = this.people[0]; //== this.st.user, avoid revealing email
496 this.st.conn.send(JSON.stringify({
497 code: "refusechallenge",
498 cid: c.id, target: c.from.sid}));
503 if (c.type == "corr")
512 localStorage.removeItem("challenge");
514 // In (almost) all cases, the challenge is consumed:
515 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
516 // NOTE: deletechallenge event might be redundant (but it's easier this way)
517 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
519 // NOTE: when launching game, the challenge is already deleted
520 launchGame: async function(c) {
521 const vModule = await import("@/variants/" + c.vname + ".js");
522 window.V = vModule.VariantRules;
523 // These game informations will be sent to other players
527 fen: c.fen || V.GenRandInitFen(),
528 players: shuffle([c.from, c.seat]), //white then black
530 vname: c.vname, //theoretically vid is enough, but much easier with vname
531 timeControl: c.timeControl,
533 let target = c.from.sid; //may not be defined if corr + offline opp
536 const opponent = this.people.find(p => p.id == c.from.id);
538 target = opponent.sid
540 const tryNotifyOpponent = () => {
541 if (!!target) //opponent is online
543 this.st.conn.send(JSON.stringify({code:"newgame",
544 gameInfo:gameInfo, target:target, cid:c.id}));
547 if (c.type == "live")
550 this.startNewGame(gameInfo);
552 else //corr: game only on server
557 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
559 gameInfo.id = response.gameId;
561 this.$router.push("/game/" + response.gameId);
565 // Send game info to everyone except opponent (and me)
566 this.st.conn.send(JSON.stringify({code:"game",
567 game: { //minimal game info:
569 players: gameInfo.players.map(p => p.name),
571 timeControl: gameInfo.timeControl,
575 // NOTE: for live games only (corr games start on the server)
576 startNewGame: function(gameInfo) {
577 const game = Object.assign({}, gameInfo, {
578 // (other) Game infos: constant
579 fenStart: gameInfo.fen,
581 // Game state (including FEN): will be updated
583 clocks: [-1, -1], //-1 = unstarted
584 initime: [0, 0], //initialized later
587 GameStorage.add(game);
588 if (this.st.settings.sound >= 1)
589 new Audio("/sounds/newgame.mp3").play().catch(err => {});
590 this.$router.push("/game/" + gameInfo.id);