3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(role="dialog" data-checkbox="modalInfo" 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#newgameDiv(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"
18 :selected="newchallenge.vid==v.id")
21 label(for="cadence") {{ st.tr["Cadence"] }} *
22 div#predefinedCadences
26 input#cadence(type="text" v-model="newchallenge.cadence"
27 placeholder="5+0, 1h+30s, 7d+1d ...")
28 fieldset(v-if="st.user.id > 0")
29 label(for="selectPlayers") {{ st.tr["Play with?"] }}
30 input#selectPlayers(type="text" v-model="newchallenge.to")
31 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
32 label(for="inputFen") FEN
33 input#inputFen(type="text" v-model="newchallenge.fen")
34 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
37 button#newGame(onClick="doClick('modalNewgame')") {{ st.tr["New game"] }}
39 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
42 button(@click="(e) => setDisplay('c','live',e)" class="active")
43 | {{ st.tr["Live challenges"] }}
44 button(@click="(e) => setDisplay('c','corr',e)")
45 | {{ st.tr["Correspondance challenges"] }}
46 ChallengeList(v-show="cdisplay=='live'"
47 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
48 ChallengeList(v-show="cdisplay=='corr'"
49 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
51 h3.text-center {{ st.tr["Who's there?"] }}
53 p(v-for="sid in Object.keys(people)" v-if="!!people[sid].name")
54 span {{ people[sid].name }}
55 // Check: anonymous players cannot send individual challenges or be challenged individually
57 v-if="sid != st.user.sid && !!st.user.name && people[sid].id > 0"
58 @click="challOrWatch(sid)"
60 | {{ getActionLabel(sid) }}
61 p.anonymous @nonymous ({{ anonymousCount }})
63 Chat(:newChat="newChat" @mychat="processChat")
67 button(@click="(e) => setDisplay('g','live',e)" class="active")
68 | {{ st.tr["Live games"] }}
69 button(@click="(e) => setDisplay('g','corr',e)")
70 | {{ st.tr["Correspondance games"] }}
71 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
72 @show-game="showGame")
73 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
74 @show-game="showGame")
78 import { store } from "@/store";
79 import { checkChallenge } from "@/data/challengeCheck";
80 import { ArrayFun } from "@/utils/array";
81 import { ajax } from "@/utils/ajax";
82 import params from "@/parameters";
83 import { getRandString, shuffle } from "@/utils/alea";
84 import Chat from "@/components/Chat.vue";
85 import GameList from "@/components/GameList.vue";
86 import ChallengeList from "@/components/ChallengeList.vue";
87 import { GameStorage } from "@/utils/gameStorage";
88 import { processModalClick } from "@/utils/modalClick";
99 cdisplay: "live", //or corr
107 vid: localStorage.getItem("vid") || "",
108 to: "", //name of challenged player (if any)
109 cadence: localStorage.getItem("cadence") || "",
116 // st.variants changes only once, at loading from [] to [...]
117 "st.variants": function(variantArray) {
118 // Set potential challenges and games variant names:
119 this.challenges.concat(this.games).forEach(o => {
121 o.vname = this.getVname(o.vid);
126 anonymousCount: function() {
128 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
132 created: function() {
133 const my = this.st.user;
134 this.$set(this.people, my.sid, {id:my.id, name:my.name, pages:["/"]});
135 // Ask server for current corr games (all but mines)
139 {uid: this.st.user.id, excluded: true},
141 this.games = this.games.concat(response.games.map(g => {
142 const type = this.classifyObject(g);
143 const vname = this.getVname(g.vid);
144 return Object.assign({}, g, {type: type, vname: vname});
148 // Also ask for corr challenges (open + sent by/to me)
152 {uid: this.st.user.id},
154 // Gather all senders names, and then retrieve full identity:
155 // (TODO [perf]: some might be online...)
157 response.challenges.forEach(c => {
158 if (c.uid != this.st.user.id)
159 names[c.uid] = ""; //unknwon for now
160 else if (!!c.target && c.target != this.st.user.id)
161 names[c.target] = "";
163 const addChallenges = (newChalls) => {
164 names[this.st.user.id] = this.st.user.name; //in case of
165 this.challenges = this.challenges.concat(
166 response.challenges.map(c => {
167 const from = {name: names[c.uid], id: c.uid}; //or just name
168 const type = this.classifyObject(c);
169 const vname = this.getVname(c.vid);
170 return Object.assign({},
175 to: (!!c.target ? names[c.target] : ""),
185 { ids: Object.keys(names).join(",") },
187 response2.users.forEach(u => {names[u.id] = u.name});
196 const connectAndPoll = () => {
197 this.send("connect");
198 this.send("pollclientsandgamers");
200 // Initialize connection
201 const connexionString = params.socketUrl +
202 "/?sid=" + this.st.user.sid +
203 "&tmpId=" + getRandString() +
204 "&page=" + encodeURIComponent(this.$route.path);
205 this.conn = new WebSocket(connexionString);
206 this.conn.onopen = connectAndPoll;
207 this.conn.onmessage = this.socketMessageListener;
208 const socketCloseListener = () => {
209 this.conn = new WebSocket(connexionString);
210 this.conn.addEventListener('message', this.socketMessageListener);
211 this.conn.addEventListener('close', socketCloseListener);
213 this.conn.onclose = socketCloseListener;
215 mounted: function() {
216 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
217 .forEach(elt => elt.addEventListener("click", processModalClick));
218 document.querySelectorAll("#predefinedCadences > button").forEach(
219 (b) => { b.addEventListener("click",
220 () => { this.newchallenge.cadence = b.innerHTML; }
224 beforeDestroy: function() {
225 this.send("disconnect");
229 send: function(code, obj) {
230 this.conn.send(JSON.stringify(
237 getVname: function(vid) {
238 const variant = this.st.variants.find(v => v.id == vid);
239 // this.st.variants might be uninitialized (variant == null)
240 return (!!variant ? variant.name : "");
242 filterChallenges: function(type) {
243 return this.challenges.filter(c => c.type == type);
245 filterGames: function(type) {
246 return this.games.filter(g => g.type == type);
248 classifyObject: function(o) { //challenge or game
249 return (o.cadence.indexOf('d') === -1 ? "live" : "corr");
251 setDisplay: function(letter, type, e) {
252 this[letter + "display"] = type;
253 e.target.classList.add("active");
254 if (!!e.target.previousElementSibling)
255 e.target.previousElementSibling.classList.remove("active");
257 e.target.nextElementSibling.classList.remove("active");
259 getActionLabel: function(sid) {
260 return this.people[sid].pages.some(p => p == "/")
264 challOrWatch: function(sid) {
265 if (this.people[sid].pages.some(p => p == "/"))
267 // Available, in Hall
268 this.newchallenge.to = this.people[sid].name;
269 doClick("modalNewgame");
273 // In some game, maybe playing maybe not
274 const gid = this.people[sid].page.match(/[a-zA-Z0-9]+$/)[0];
275 this.showGame(this.games.find(g => g.id == gid)), sid;
278 showGame: function(g, obsId) {
279 // NOTE: we are an observer, since only games I don't play are shown here
280 // ==> Moves sent by connected remote player(s) if live game
281 let url = "/game/" + g.id;
282 if (g.type == "live")
287 if (this.people[g.players[i].sid].pages.indexOf(url) >= 0)
288 rids.push(g.players[i].sid);
291 rids.push(obsId); //observer can provide game too
292 const ridIdx = Math.floor(Math.random() * rids.length);
293 url += "?rid=" + rids[ridIdx];
295 this.$router.push(url);
297 processChat: function(chat) {
298 this.send("newchat", {data:chat});
301 socketMessageListener: function(msg) {
302 const data = JSON.parse(msg.data);
305 case "pollclientsandgamers":
307 let identityAsked = {};
308 data.sockIds.forEach(s => {
309 if (s.sid != this.st.user.sid && !identityAsked[s.sid])
311 identityAsked[s.sid] = true;
312 this.send("askidentity", {target:s.sid});
314 if (!this.people[s.sid])
315 this.$set(this.people, s.sid, {id:0, name:"", pages:[s.page || "/"]});
316 else if (!!s.page && this.people[s.sid].pages.indexOf(s.page) < 0)
317 this.people[s.sid].pages.push(s.page);
319 this.send("askchallenge", {target:s.sid});
321 this.send("askgame", {target:s.sid});
327 // NOTE: player could have been polled earlier, but might have logged in then
328 // So it's a good idea to ask identity if he was anonymous.
329 // But only ask game / challenge if currently disconnected.
330 if (!this.people[data.from])
332 this.$set(this.people, data.from, {name:"", id:0, pages:[data.page]});
333 if (data.code == "connect")
334 this.send("askchallenge", {target:data.from});
336 this.send("askgame", {target:data.from});
340 // append page if not already in list
341 if (this.people[data.from].pages.indexOf(data.page) < 0)
342 this.people[data.from].pages.push(data.page);
344 if (this.people[data.from].id == 0)
345 this.send("askidentity", {target:data.from});
349 // Disconnect means no more tmpIds:
350 if (data.code == "disconnect")
352 this.$delete(this.people, data.from);
353 // Also remove all challenges sent by this player:
354 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
358 const pidx = this.people[data.from].pages.indexOf(data.page);
359 this.people[data.from].pages.splice(pageIdx, 1);
360 if (this.people[data.from].pages.length == 0)
362 this.$delete(this.people, data.from);
363 // And all live games where he plays and no other opponent is online
364 ArrayFun.remove(this.games, g =>
365 g.type == "live" && (g.players.every(p => p.sid == data.from
366 || !this.people[p.sid])), "all");
371 // Request for identification: reply if I'm not anonymous
372 if (this.st.user.id > 0)
375 // NOTE: decompose to avoid revealing email
376 name: this.st.user.name,
377 sid: this.st.user.sid,
380 this.send("identity", {data:me, target:data.from});
385 const user = data.data;
386 this.$set(this.people, user.sid,
390 pages: this.people[user.sid].pages,
393 // // TODO: smarter, if multi-connect, send to all instances... (several sid's)
394 // // Or better: just prevent multi-connect.
395 // // Fix anomaly: if registered player multi-connect, should be left only one
396 // const anomalies = Object.keys(this.people).filter(sid => this.people[sid].id == user.id);
397 // if (anomalies.length == 2)
398 // this.$delete(this.people, anomalies[0]);
399 // // --> this isn't good, some sid's are just forgetted
405 // Send my current live challenge (if any)
406 const cIdx = this.challenges.findIndex(c =>
407 c.from.sid == this.st.user.sid && c.type == "live");
410 const c = this.challenges[cIdx];
411 // NOTE: in principle, should only send targeted challenge to the target.
412 // But we may not know yet the identity of the target (just name),
413 // so cannot decide if data.from is the target or not.
417 from: this.st.user.sid,
424 this.send("challenge", {data:myChallenge, target:data.from});
428 case "challenge": //after "askchallenge"
431 // NOTE about next condition: see "askchallenge" case.
432 const chall = data.data;
433 if (!chall.to || (this.people[chall.from].id > 0 &&
434 (chall.from == this.st.user.sid || chall.to == this.st.user.name)))
436 let newChall = Object.assign({}, chall);
437 newChall.type = this.classifyObject(chall);
438 newChall.added = Date.now();
439 let fromValues = Object.assign({}, this.people[chall.from]);
440 delete fromValues["pages"]; //irrelevant in this context
441 newChall.from = Object.assign({sid:chall.from}, fromValues);
442 newChall.vname = this.getVname(newChall.vid);
443 this.challenges.push(newChall);
447 case "refusechallenge":
449 const cid = data.data;
450 ArrayFun.remove(this.challenges, c => c.id == cid);
451 alert(this.st.tr["Challenge declined"]);
454 case "deletechallenge":
456 // NOTE: the challenge may be already removed
457 const cid = data.data;
458 ArrayFun.remove(this.challenges, c => c.id == cid);
461 case "game": //individual request
464 // NOTE: it may be live or correspondance
465 const game = data.data;
466 if (this.games.findIndex(g => g.id == game.id) < 0)
469 newGame.type = this.classifyObject(game);
470 newGame.vname = this.getVname(game.vid);
471 if (!game.score) //if new game from Hall
473 this.games.push(newGame);
479 // New game just started: data contain all information
480 const gameInfo = data.data;
481 if (this.classifyObject(gameInfo) == "live")
482 this.startNewGame(gameInfo);
485 this.infoMessage = this.st.tr["New correspondance game:"] +
486 " <a href='#/game/" + gameInfo.id + "'>" +
487 "#/game/" + gameInfo.id + "</a>";
488 let modalBox = document.getElementById("modalInfo");
489 modalBox.checked = true;
490 setTimeout(() => { modalBox.checked = false; }, 3000);
495 this.newChat = data.data;
499 // Challenge lifecycle:
500 newChallenge: async function() {
501 if (this.newchallenge.vid == "")
502 return alert(this.st.tr["Please select a variant"]);
503 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
504 return alert(this.st.tr["Self-challenge is forbidden"]);
505 const vname = this.getVname(this.newchallenge.vid);
506 const vModule = await import("@/variants/" + vname + ".js");
507 window.V = vModule.VariantRules;
508 if (!!this.newchallenge.cadence.match(/^[0-9]+$/))
509 this.newchallenge.cadence += "+0"; //assume minutes, no increment
510 const error = checkChallenge(this.newchallenge);
513 const ctype = this.classifyObject(this.newchallenge);
514 if (ctype == "corr" && this.st.user.id <= 0)
515 return alert(this.st.tr["Please log in to play correspondance games"]);
516 // NOTE: "from" information is not required here
517 let chall = Object.assign({}, this.newchallenge);
518 const finishAddChallenge = (cid) => {
519 chall.id = cid || "c" + getRandString();
520 // Remove old challenge if any (only one at a time of a given type):
521 const cIdx = this.challenges.findIndex(c =>
522 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
525 // Delete current challenge (will be replaced now)
526 this.send("deletechallenge", {data:this.challenges[cIdx].id});
532 {id: this.challenges[cIdx].id}
535 this.challenges.splice(cIdx, 1);
537 this.send("newchallenge", {data:Object.assign({from:this.st.user.sid}, chall)});
538 // Add new challenge:
539 chall.from = { //decompose to avoid revealing email
540 sid: this.st.user.sid,
542 name: this.st.user.name,
544 chall.added = Date.now();
545 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
548 this.challenges.push(chall);
549 // Remember cadence + vid for quicker further challenges:
550 localStorage.setItem("cadence", chall.cadence);
551 localStorage.setItem("vid", chall.vid);
552 document.getElementById("modalNewgame").checked = false;
556 // Live challenges have a random ID
557 finishAddChallenge(null);
561 // Correspondance game: send challenge to server
566 response => { finishAddChallenge(response.cid); }
570 clickChallenge: function(c) {
571 const myChallenge = (c.from.sid == this.st.user.sid //live
572 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
575 if (c.type == "corr" && this.st.user.id <= 0)
576 return alert(this.st.tr["Please log in to accept corr challenges"]);
578 if (!!c.to) //c.to == this.st.user.name (connected)
580 // TODO: if special FEN, show diagram after loading variant
581 c.accepted = confirm("Accept challenge?");
585 c.seat = { //again, avoid c.seat = st.user to not reveal email
586 sid: this.st.user.sid,
588 name: this.st.user.name,
594 this.send("refusechallenge", {data:c.id, target:c.from.sid});
596 this.send("deletechallenge", {data:c.id});
600 if (c.type == "corr")
608 this.send("deletechallenge", {data:c.id});
610 // In all cases, the challenge is consumed:
611 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
613 // NOTE: when launching game, the challenge is already being deleted
614 launchGame: async function(c) {
615 const vModule = await import("@/variants/" + c.vname + ".js");
616 window.V = vModule.VariantRules;
617 // These game informations will be shared
621 fen: c.fen || V.GenRandInitFen(),
622 players: shuffle([c.from, c.seat]), //white then black
626 let oppsid = c.from.sid; //may not be defined if corr + offline opp
629 oppsid = Object.keys(this.people).find(sid =>
630 this.people[sid].id == c.from.id);
632 const notifyNewgame = () => {
633 if (!!oppsid) //opponent is online
634 this.send("startgame", {data:gameInfo, target:oppsid});
635 // Send game info (only if live) to everyone except me in this tab
636 this.send("newgame", {data:gameInfo});
638 if (c.type == "live")
641 this.startNewGame(gameInfo);
643 else //corr: game only on server
648 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
650 gameInfo.id = response.gameId;
652 this.$router.push("/game/" + response.gameId);
657 // NOTE: for live games only (corr games start on the server)
658 startNewGame: function(gameInfo) {
659 const game = Object.assign({}, gameInfo, {
660 // (other) Game infos: constant
661 fenStart: gameInfo.fen,
662 vname: this.getVname(gameInfo.vid),
664 // Game state (including FEN): will be updated
666 clocks: [-1, -1], //-1 = unstarted
667 initime: [0, 0], //initialized later
670 GameStorage.add(game);
671 if (this.st.settings.sound >= 1)
672 new Audio("/sounds/newgame.mp3").play().catch(err => {});
673 this.$router.push("/game/" + gameInfo.id);
679 <style lang="sass" scoped>
684 margin: 10px auto 5px auto
695 @media screen and (max-width: 767px)