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 New game started: #[a(href="/game/" + {{ newGameId }})]
9 input#modalNewgame.modal(type="checkbox")
10 div(role="dialog" aria-labelledby="titleFenedit")
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: [], //(all) online players
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 = {id:0, name:"@nonymous", count:0};
122 this.people.forEach(p => {
128 if (anonymous.count > 0)
129 playerList.push(anonymous);
133 created: function() {
134 // Always add myself to players' list
135 const my = this.st.user;
136 this.people.push({sid:my.sid, id:my.id, name:my.name});
137 // Retrieve live challenge (not older than 30 minute) if any:
138 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
141 if ((Date.now() - chall.added)/1000 <= 30*60)
142 this.challenges.push(chall);
144 localStorage.removeItem("challenge");
146 if (this.st.user.id > 0)
148 // Ask server for current corr games (all but mines)
152 {uid: this.st.user.id, excluded: true},
154 this.games = this.games.concat(response.games.map(g => {
155 const type = this.classifyObject(g);
156 const vname = this.getVname(g.vid);
157 return Object.assign({}, g, {type: type, vname: vname});
161 // Also ask for corr challenges (open + sent to me)
165 {uid: this.st.user.id},
167 // Gather all senders names, and then retrieve full identity:
168 // (TODO [perf]: some might be online...)
169 const uids = response.challenges.map(c => { return c.uid });
172 { ids: uids.join(",") },
175 response2.users.forEach(u => {names[u.id] = u.name});
176 this.challenges = this.challenges.concat(
177 response.challenges.map(c => {
178 // (just players names in fact)
179 const from = {name: names[c.uid], id: c.uid};
180 const type = this.classifyObject(c);
181 const vname = this.getVname(c.vid);
182 return Object.assign({}, c, {type: type, vname: vname, from: from});
190 // 0.1] Ask server for room composition:
191 const funcPollClients = () => {
192 this.st.conn.send(JSON.stringify({code:"pollclients"}));
194 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
196 else //socket not ready yet (initial loading)
197 this.st.conn.onopen = funcPollClients;
198 this.st.conn.onmessage = this.socketMessageListener;
199 const socketCloseListener = () => {
200 store.socketCloseListener(); //reinitialize connexion (in store.js)
201 this.st.conn.addEventListener('message', this.socketMessageListener);
202 this.st.conn.addEventListener('close', socketCloseListener);
204 this.st.conn.onclose = socketCloseListener;
208 filterChallenges: function(type) {
209 return this.challenges.filter(c => c.type == type);
211 filterGames: function(type) {
212 return this.games.filter(g => g.type == type);
214 classifyObject: function(o) { //challenge or game
215 // Heuristic: should work for most cases... (TODO)
216 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
218 showGame: function(g) {
219 // NOTE: we are an observer, since only games I don't play are shown here
220 // ==> Moves sent by connected remote player(s) if live game
221 let url = "/game/" + g.id;
222 if (g.type == "live")
224 const remotes = g.players.filter(p => this.people.some(pl => pl.sid == p.sid));
225 const rIdx = (remotes.length == 1 ? 0 : Math.floor(Math.random()*2));
226 url += "?rid=" + remotes[rIdx].sid;
228 this.$router.push(url);
230 // TODO: ...filter(...)[0].name, one-line, just remove this function
231 getVname: function(vid) {
232 const vIdx = this.st.variants.findIndex(v => v.id == vid);
233 return vIdx >= 0 ? this.st.variants[vIdx].name : "";
235 getSid: function(pname) {
236 const pIdx = this.people.findIndex(pl => pl.name == pname);
237 return (pIdx === -1 ? null : this.people[pIdx].sid);
239 getPname: function(sid) {
240 const pIdx = this.people.findIndex(pl => pl.sid == sid);
241 return (pIdx === -1 ? null : this.people[pIdx].name);
243 sendSomethingTo: function(to, code, obj, warnDisconnected) {
244 const doSend = (code, obj, sid) => {
245 this.st.conn.send(JSON.stringify(Object.assign(
254 // Challenge with targeted players
255 const targetSid = this.getSid(to);
258 if (!!warnDisconnected)
259 alert("Warning: " + pname + " is not connected");
262 doSend(code, obj, targetSid);
266 // Open challenge: send to all connected players (except us)
267 this.people.forEach(p => {
268 if (p.sid != this.st.user.sid) //only sid is always set
269 doSend(code, obj, p.sid);
274 socketMessageListener: function(msg) {
275 const data = JSON.parse(msg.data);
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}));
286 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
292 // Request for identification: reply if I'm not anonymous
293 if (this.st.user.id > 0)
295 this.st.conn.send(JSON.stringify(
296 // people[0] instead of st.user to avoid sending email
297 {code:"identity", user:this.people[0], target:data.from}));
303 // Send my current live challenge (if any)
304 const cIdx = this.challenges
305 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
308 const c = this.challenges[cIdx];
311 // Minimal challenge informations: (from not required)
316 timeControl: c.timeControl
318 this.st.conn.send(JSON.stringify({code:"challenge",
319 chall:myChallenge, target:data.from}));
325 // Send my current live game (if any)
326 GameStorage.getCurrent((game) => {
331 // Minimal game informations:
333 players: game.players.map(p => p.name),
335 timeControl: game.timeControl,
337 this.st.conn.send(JSON.stringify({code:"game",
338 game:myGame, target:data.from}));
345 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
346 this.people[pIdx].id = data.user.id;
347 this.people[pIdx].name = data.user.name;
352 // Receive challenge from some player (+sid)
353 let newChall = data.chall;
354 newChall.type = this.classifyObject(data.chall);
355 const pIdx = this.people.findIndex(p => p.sid == data.from);
356 newChall.from = this.people[pIdx]; //may be anonymous
357 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
358 newChall.vname = this.getVname(newChall.vid);
359 this.challenges.push(newChall);
364 // Receive game from some player (+sid)
365 // NOTE: it may be correspondance (if newgame while we are connected)
366 if (!this.games.some(g => g.id == data.game.id)) //ignore duplicates
368 let newGame = data.game;
369 newGame.type = this.classifyObject(data.game);
370 newGame.vname = this.getVname(data.game.vid);
371 newGame.rid = data.from;
373 this.games.push(newGame);
379 // TODO: next line required ?!
380 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
381 // New game just started: data contain all information
382 if (this.classifyObject(data.gameInfo) == "live")
383 this.startNewGame(data.gameInfo);
386 this.newGameId = data.gameInfo.gameId;
387 let modalBox = document.getElementById("modalInfo");
388 modalBox.checked = true;
389 setTimeout(() => { modalBox.checked = false; }, 2500);
393 case "refusechallenge":
395 alert(this.getPname(data.from) + " declined your challenge");
396 ArrayFun.remove(this.challenges, c => c.id == data.cid);
399 case "deletechallenge":
401 // NOTE: the challenge may be already removed
402 ArrayFun.remove(this.challenges, c => c.id == data.cid);
403 localStorage.removeItem("challenge"); //in case of
408 this.people.push({name:"", id:0, sid:data.sid});
409 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
410 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
411 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
416 ArrayFun.remove(this.people, p => p.sid == data.sid);
417 // Also remove all challenges sent by this player:
418 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
419 // And all live games where he plays and no other opponent is online
420 ArrayFun.remove(this.games, g =>
421 g.type == "live" && (g.players.every(p => p.sid == data.sid
422 || !this.people.some(pl => pl.sid == p.sid))), "all");
427 // Challenge lifecycle:
428 tryChallenge: function(player) {
430 return; //anonymous players cannot be challenged
431 this.newchallenge.to = player.name;
432 doClick("modalNewgame");
434 newChallenge: async function() {
435 const vname = this.getVname(this.newchallenge.vid);
436 const vModule = await import("@/variants/" + vname + ".js");
437 window.V = vModule.VariantRules;
438 const error = checkChallenge(this.newchallenge);
441 const ctype = this.classifyObject(this.newchallenge);
442 if (ctype == "corr" && this.st.user.id <= 0)
443 return alert("Please log in to play correspondance games");
444 // NOTE: "from" information is not required here
445 let chall = Object.assign({}, this.newchallenge);
446 const finishAddChallenge = (cid,warnDisconnected) => {
447 chall.id = cid || "c" + getRandString();
448 // Send challenge to peers (if connected)
449 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
450 chall.added = Date.now();
451 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
454 chall.from = this.people[0]; //avoid sending email
455 this.challenges.push(chall);
456 localStorage.setItem("challenge", JSON.stringify(chall));
457 document.getElementById("modalNewgame").checked = false;
459 const cIdx = this.challenges.findIndex(
460 c => c.from.sid == this.st.user.sid && c.type == ctype);
463 // Delete current challenge (will be replaced now)
464 this.sendSomethingTo(this.challenges[cIdx].to,
465 "deletechallenge", {cid:this.challenges[cIdx].id});
471 {id: this.challenges[cIdx].id}
474 this.challenges.splice(cIdx, 1);
478 // Live challenges have a random ID
479 finishAddChallenge(null, "warnDisconnected");
483 // Correspondance game: send challenge to server
488 response => { finishAddChallenge(response.cid); }
492 clickChallenge: function(c) {
493 // In all cases, the challenge is consumed:
494 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
495 // NOTE: deletechallenge event might be redundant (but it's easier this way)
496 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
497 const myChallenge = (c.from.sid == this.st.user.sid //live
498 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
502 if (!!c.to) //c.to == this.st.user.name (connected)
504 // TODO: if special FEN, show diagram after loading variant
505 c.accepted = confirm("Accept challenge?");
509 c.seat = this.people[0]; //== this.st.user, avoid revealing email
514 this.st.conn.send(JSON.stringify({
515 code: "refusechallenge",
516 cid: c.id, target: c.from.sid}));
521 localStorage.removeItem("challenge");
522 if (c.type == "corr")
532 // NOTE: when launching game, the challenge is already deleted
533 launchGame: async function(c) {
534 const vModule = await import("@/variants/" + c.vname + ".js");
535 window.V = vModule.VariantRules;
536 // These game informations will be sent to other players
539 gameId: getRandString(),
540 fen: c.fen || V.GenRandInitFen(),
541 players: shuffle([c.from, c.seat]), //white then black
543 timeControl: c.timeControl,
545 let target = c.from.sid; //may not be defined if corr + offline opp
548 const opponent = this.people.find(p => p.id == c.from.id);
550 target = opponent.sid
552 if (!!target) //opponent is online
554 this.st.conn.send(JSON.stringify({code:"newgame",
555 gameInfo:gameInfo, target:target, cid:c.id}));
557 if (c.type == "live")
558 this.startNewGame(gameInfo);
559 else //corr: game only on server
564 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
565 response => { this.$router.push("/game/" + response.gameId); }
569 // NOTE: for live games only (corr games start on the server)
570 startNewGame: function(gameInfo) {
571 const game = Object.assign({}, gameInfo, {
572 // (other) Game infos: constant
573 fenStart: gameInfo.fen,
575 // Game state (including FEN): will be updated
577 clocks: [-1, -1], //-1 = unstarted
578 initime: [0, 0], //initialized later
581 GameStorage.add(game);
582 if (this.st.settings.sound >= 1)
583 new Audio("/sounds/newgame.mp3").play().catch(err => {});
584 this.$router.push("/game/" + gameInfo.gameId);