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" data-checkbox="modalNewgame"
11 aria-labelledby="titleFenedit")
12 .card.smallpad(@keyup.enter="newChallenge")
13 label#closeNewgame.modal-close(for="modalNewgame")
15 label(for="selectVariant") {{ st.tr["Variant"] }}
16 select#selectVariant(v-model="newchallenge.vid")
17 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
19 label(for="timeControl") {{ st.tr["Time control"] }}
20 input#timeControl(type="text" v-model="newchallenge.timeControl"
21 placeholder="3m+2s, 1h+30s, 7d+1d ...")
22 fieldset(v-if="st.user.id > 0")
23 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
24 input#selectPlayers(type="text" v-model="newchallenge.to")
25 fieldset(v-if="st.user.id > 0")
26 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
27 input#inputFen(type="text" v-model="newchallenge.fen")
28 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
31 button#newGame(onClick="doClick('modalNewgame')") New game
33 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
36 button(@click="(e) => setDisplay('c','live',e)" class="active")
38 button(@click="(e) => setDisplay('c','corr',e)")
39 | 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")
45 h3.text-center Who's there?
47 p(v-for="p in Object.values(people)" v-if="!!p.name")
50 v-if="p.name != st.user.name"
51 @click="challOrWatch(p,$event)"
53 | {{ whatPlayerDoes(p) }}
54 p.anonymous @nonymous ({{ anonymousCount }})
60 button(@click="(e) => setDisplay('g','live',e)" class="active")
62 button(@click="(e) => setDisplay('g','corr',e)")
63 | 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 Chat from "@/components/Chat.vue";
77 import GameList from "@/components/GameList.vue";
78 import ChallengeList from "@/components/ChallengeList.vue";
79 import { GameStorage } from "@/utils/gameStorage";
90 cdisplay: "live", //or corr
91 pdisplay: "players", //or chat
95 people: {}, //people in main hall
100 to: "", //name of challenged player (if any)
101 timeControl: "", //"2m+2s" ...etc
106 // st.variants changes only once, at loading from [] to [...]
107 "st.variants": function(variantArray) {
108 // Set potential challenges and games variant names:
109 this.challenges.forEach(c => {
111 c.vname = this.getVname(c.vid);
113 this.games.forEach(g => {
115 g.vname = this.getVname(g.vid);
120 anonymousCount: function() {
122 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
126 created: function() {
127 // Always add myself to players' list
128 const my = this.st.user;
129 this.$set(this.people, my.sid, {id:my.id, name:my.name});
130 // Retrieve live challenge (not older than 30 minute) if any:
131 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
134 if ((Date.now() - chall.added)/1000 <= 30*60)
135 this.challenges.push(chall);
137 localStorage.removeItem("challenge");
139 // Ask server for current corr games (all but mines)
143 {uid: this.st.user.id, excluded: true},
145 this.games = this.games.concat(response.games.map(g => {
146 const type = this.classifyObject(g);
147 const vname = this.getVname(g.vid);
148 return Object.assign({}, g, {type: type, vname: vname});
152 // Also ask for corr challenges (open + sent to me)
156 {uid: this.st.user.id},
158 // Gather all senders names, and then retrieve full identity:
159 // (TODO [perf]: some might be online...)
160 const uids = response.challenges.map(c => { return c.uid });
163 { ids: uids.join(",") },
166 response2.users.forEach(u => {names[u.id] = u.name});
167 this.challenges = this.challenges.concat(
168 response.challenges.map(c => {
169 // (just players names in fact)
170 const from = {name: names[c.uid], id: c.uid};
171 const type = this.classifyObject(c);
172 const vname = this.getVname(c.vid);
173 return Object.assign({}, c, {type: type, vname: vname, from: from});
180 // 0.1] Ask server for room composition:
181 const funcPollClients = () => {
182 // Same strategy as in Game.vue: send connection
183 // after we're sure WebSocket is initialized
184 this.st.conn.send(JSON.stringify({code:"connect"}));
185 this.st.conn.send(JSON.stringify({code:"pollclients"}));
187 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
189 else //socket not ready yet (initial loading)
190 this.st.conn.onopen = funcPollClients;
191 this.st.conn.onmessage = this.socketMessageListener;
192 const socketCloseListener = () => {
193 store.socketCloseListener(); //reinitialize connexion (in store.js)
194 this.st.conn.addEventListener('message', this.socketMessageListener);
195 this.st.conn.addEventListener('close', socketCloseListener);
197 this.st.conn.onclose = socketCloseListener;
201 filterChallenges: function(type) {
202 return this.challenges.filter(c => c.type == type);
204 filterGames: function(type) {
205 return this.games.filter(g => g.type == type);
207 classifyObject: function(o) { //challenge or game
208 // Heuristic: should work for most cases... (TODO)
209 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
211 showGame: function(g) {
212 // NOTE: we are an observer, since only games I don't play are shown here
213 // ==> Moves sent by connected remote player(s) if live game
214 let url = "/game/" + g.id;
215 if (g.type == "live")
216 url += "?rid=" + g.rid;
217 this.$router.push(url);
219 setDisplay: function(letter, type, e) {
220 this[letter + "display"] = type;
221 e.target.classList.add("active");
222 if (!!e.target.previousElementSibling)
223 e.target.previousElementSibling.classList.remove("active");
225 e.target.nextElementSibling.classList.remove("active");
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 whatPlayerDoes: function(p) {
233 if (this.games.some(g => g.type == "live"
234 && g.players.some(pl => pl.sid == p.sid)))
238 return "Challenge"; //player is available
240 sendSomethingTo: function(to, code, obj, warnDisconnected) {
241 const doSend = (code, obj, sid) => {
242 this.st.conn.send(JSON.stringify(Object.assign(
250 // Challenge with targeted players
252 Object.keys(this.people).find(sid => this.people[sid].name == to);
255 if (!!warnDisconnected)
256 alert("Warning: " + to + " is not connected");
260 doSend(code, obj, targetSid);
264 // Open challenge: send to all connected players (me excepted)
265 Object.keys(this.people).forEach(sid => {
266 if (sid != this.st.user.sid)
267 doSend(code, obj, sid);
273 socketMessageListener: function(msg) {
274 const data = JSON.parse(msg.data);
278 alert("Warning: duplicate 'offline' connection");
280 // 0.2] Receive clients list (just socket IDs)
283 data.sockIds.forEach(sid => {
284 this.$set(this.people, sid, {id:0, name:""});
285 // Ask identity, challenges and game(s)
286 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
287 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
289 // Also ask current games to all playing peers (TODO: some design issue)
290 this.st.conn.send(JSON.stringify({code:"askgames"}));
295 // Request for identification: reply if I'm not anonymous
296 if (this.st.user.id > 0)
298 this.st.conn.send(JSON.stringify({code:"identity",
300 // NOTE: decompose to avoid revealing email
301 name: this.st.user.name,
302 sid: this.st.user.sid,
311 this.$set(this.people, data.user.sid,
312 {id: data.user.id, name: data.user.name});
317 // Send my current live challenge (if any)
318 const cIdx = this.challenges.findIndex(c =>
319 c.from.sid == this.st.user.sid && c.type == "live");
322 const c = this.challenges[cIdx];
325 // Only share targeted challenges to the targets:
326 const toSid = Object.keys(this.people).find(k =>
327 this.people[k].name == c.to);
328 if (toSid != data.from)
333 // Minimal challenge informations: (from not required)
338 timeControl: c.timeControl,
340 this.st.conn.send(JSON.stringify({code:"challenge",
341 chall:myChallenge, target:data.from}));
347 // Receive challenge from some player (+sid)
348 let newChall = data.chall;
349 newChall.type = this.classifyObject(data.chall);
351 Object.assign({sid:data.from}, this.people[data.from]);
352 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
353 newChall.vname = this.getVname(newChall.vid);
354 this.challenges.push(newChall);
359 // Receive game from some player (+sid)
360 // NOTE: it may be correspondance (if newgame while we are connected)
361 if (this.games.every(g => g.id != data.game.id)) //ignore duplicates
363 let newGame = data.game;
364 newGame.type = this.classifyObject(data.game);
365 newGame.vname = this.getVname(data.game.vid);
366 newGame.rid = data.from;
368 this.games.push(newGame);
374 // TODO: next line required ?!
375 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
376 // New game just started: data contain all information
377 if (this.classifyObject(data.gameInfo) == "live")
378 this.startNewGame(data.gameInfo);
381 this.infoMessage = "New game started: " +
382 "<a href='#/game/" + data.gameInfo.id + "'>" +
383 "#/game/" + data.gameInfo.id + "</a>";
384 let modalBox = document.getElementById("modalInfo");
385 modalBox.checked = true;
386 setTimeout(() => { modalBox.checked = false; }, 3000);
390 case "refusechallenge":
392 ArrayFun.remove(this.challenges, c => c.id == data.cid);
393 alert(this.people[data.from].name + " declined your challenge");
396 case "deletechallenge":
398 // NOTE: the challenge may be already removed
399 ArrayFun.remove(this.challenges, c => c.id == data.cid);
400 localStorage.removeItem("challenge"); //in case of
405 this.$set(this.people, data.from, {name:"", id:0});
406 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
407 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
408 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
413 this.$delete(this.people, data.from);
414 // Also remove all challenges sent by this player:
415 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
416 // And all live games where he plays and no other opponent is online
417 ArrayFun.remove(this.games, g =>
418 g.type == "live" && (g.players.every(p => p.sid == data.from
419 || !this.people[p.sid])), "all");
424 // Challenge lifecycle:
425 tryChallenge: function(player) {
427 return; //anonymous players cannot be challenged
428 this.newchallenge.to = player.name;
429 doClick("modalNewgame");
431 challOrWatch: function(p, e) {
432 switch (e.target.innerHTML)
435 this.tryChallenge(p);
438 // NOTE: this search for game was already done for rendering
439 this.showGame(this.games.find(
440 g => g.type=="live" && g.players.some(pl => pl.sid == p.sid)));
444 newChallenge: async function() {
445 const vname = this.getVname(this.newchallenge.vid);
446 const vModule = await import("@/variants/" + vname + ".js");
447 window.V = vModule.VariantRules;
448 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
449 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
450 const error = checkChallenge(this.newchallenge);
453 const ctype = this.classifyObject(this.newchallenge);
454 if (ctype == "corr" && this.st.user.id <= 0)
455 return alert("Please log in to play correspondance games");
456 // NOTE: "from" information is not required here
457 let chall = Object.assign({}, this.newchallenge);
458 const finishAddChallenge = (cid,warnDisconnected) => {
459 chall.id = cid || "c" + getRandString();
460 // Send challenge to peers (if connected)
461 const isSent = this.sendSomethingTo(chall.to, "challenge",
462 {chall:chall}, !!warnDisconnected);
465 // Remove old challenge if any (only one at a time):
466 const cIdx = this.challenges.findIndex(c =>
467 c.from.sid == this.st.user.sid && c.type == ctype);
470 // Delete current challenge (will be replaced now)
471 this.sendSomethingTo(this.challenges[cIdx].to,
472 "deletechallenge", {cid:this.challenges[cIdx].id});
478 {id: this.challenges[cIdx].id}
481 this.challenges.splice(cIdx, 1);
483 // Add new challenge:
484 chall.added = Date.now();
485 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
488 chall.from = { //decompose to avoid revealing email
489 sid: this.st.user.sid,
491 name: this.st.user.name,
493 this.challenges.push(chall);
495 localStorage.setItem("challenge", JSON.stringify(chall));
496 document.getElementById("modalNewgame").checked = false;
500 // Live challenges have a random ID
501 finishAddChallenge(null, "warnDisconnected");
505 // Correspondance game: send challenge to server
510 response => { finishAddChallenge(response.cid); }
514 clickChallenge: function(c) {
515 const myChallenge = (c.from.sid == this.st.user.sid //live
516 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
519 if (c.type == "corr" && this.st.user.id <= 0)
520 return alert("Please log in to accept corr challenges");
522 if (!!c.to) //c.to == this.st.user.name (connected)
524 // TODO: if special FEN, show diagram after loading variant
525 c.accepted = confirm("Accept challenge?");
529 c.seat = { //again, avoid c.seat = st.user to not reveal email
530 sid: this.st.user.sid,
532 name: this.st.user.name,
538 this.st.conn.send(JSON.stringify({
539 code: "refusechallenge",
540 cid: c.id, target: c.from.sid}));
542 this.sendSomethingTo((!!c.to ? c.from : null), "deletechallenge", {cid:c.id});
546 if (c.type == "corr")
555 localStorage.removeItem("challenge");
556 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
558 // In all cases, the challenge is consumed:
559 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
561 // NOTE: when launching game, the challenge is already deleted
562 launchGame: async function(c) {
563 const vModule = await import("@/variants/" + c.vname + ".js");
564 window.V = vModule.VariantRules;
565 // These game informations will be sent to other players
569 fen: c.fen || V.GenRandInitFen(),
570 players: shuffle([c.from, c.seat]), //white then black
572 vname: c.vname, //theoretically vid is enough, but much easier with vname
573 timeControl: c.timeControl,
575 let oppsid = c.from.sid; //may not be defined if corr + offline opp
578 oppsid = Object.keys(this.people).find(sid =>
579 this.people[sid].id == c.from.id);
581 const tryNotifyOpponent = () => {
582 if (!!oppsid) //opponent is online
584 this.st.conn.send(JSON.stringify({code:"newgame",
585 gameInfo:gameInfo, target:oppsid, cid:c.id}));
588 if (c.type == "live")
591 this.startNewGame(gameInfo);
593 else //corr: game only on server
598 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
600 gameInfo.id = response.gameId;
602 this.$router.push("/game/" + response.gameId);
606 // Send game info to everyone except opponent (and me)
607 const playersNames = gameInfo.players.map(p => {name: p.name});
608 Object.keys(this.people).forEach(sid => {
609 if (![this.st.user.sid,target].includes(sid))
611 this.st.conn.send(JSON.stringify({code:"game",
612 game: { //minimal game info:
614 players: playersNames,
616 timeControl: gameInfo.timeControl,
622 // NOTE: for live games only (corr games start on the server)
623 startNewGame: function(gameInfo) {
624 const game = Object.assign({}, gameInfo, {
625 // (other) Game infos: constant
626 fenStart: gameInfo.fen,
628 // Game state (including FEN): will be updated
630 clocks: [-1, -1], //-1 = unstarted
631 initime: [0, 0], //initialized later
634 GameStorage.add(game);
635 if (this.st.settings.sound >= 1)
636 new Audio("/sounds/newgame.mp3").play().catch(err => {});
637 this.$router.push("/game/" + gameInfo.id);
643 <style lang="sass" scoped>
648 margin: 10px auto 5px auto
659 @media screen and (max-width: 767px)