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="timeControl") {{ st.tr["Time control"] }} *
22 div#predefinedTimeControls
26 input#timeControl(type="text" v-model="newchallenge.timeControl"
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="p in Object.values(people)" v-if="!!p.name")
56 v-if="p.name != st.user.name"
57 @click="challOrWatch(p,$event)"
59 | {{ whatPlayerDoes(p) }}
60 p.anonymous @nonymous ({{ anonymousCount }})
66 button(@click="(e) => setDisplay('g','live',e)" class="active")
67 | {{ st.tr["Live games"] }}
68 button(@click="(e) => setDisplay('g','corr',e)")
69 | {{ st.tr["Correspondance games"] }}
70 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
71 @show-game="showGame")
72 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
73 @show-game="showGame")
77 import { store } from "@/store";
78 import { checkChallenge } from "@/data/challengeCheck";
79 import { ArrayFun } from "@/utils/array";
80 import { ajax } from "@/utils/ajax";
81 import { getRandString, shuffle } from "@/utils/alea";
82 import Chat from "@/components/Chat.vue";
83 import GameList from "@/components/GameList.vue";
84 import ChallengeList from "@/components/ChallengeList.vue";
85 import { GameStorage } from "@/utils/gameStorage";
86 import { processModalClick } from "@/utils/modalClick";
98 cdisplay: "live", //or corr
99 pdisplay: "players", //or chat
103 people: {}, //people in main hall
107 vid: localStorage.getItem("vid") || "",
108 to: "", //name of challenged player (if any)
109 timeControl: localStorage.getItem("timeControl") || "",
114 // st.variants changes only once, at loading from [] to [...]
115 "st.variants": function(variantArray) {
116 // Set potential challenges and games variant names:
117 this.challenges.forEach(c => {
119 c.vname = this.getVname(c.vid);
121 this.games.forEach(g => {
123 g.vname = this.getVname(g.vid);
128 anonymousCount: function() {
130 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
134 created: function() {
135 // Always add myself to players' list
136 const my = this.st.user;
137 this.$set(this.people, my.sid, {id:my.id, name:my.name});
138 // Retrieve live challenge (not older than 30 minute) if any:
139 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
142 // NOTE: a challenge survives 3 minutes, for potential connection issues
143 if ((Date.now() - chall.added)/1000 <= 3*60)
145 chall.added = Date.now(); //update added time, for next disconnect...
146 this.challenges.push(chall);
147 localStorage.setItem("challenge", JSON.stringify(chall));
150 localStorage.removeItem("challenge");
152 // Ask server for current corr games (all but mines)
156 {uid: this.st.user.id, excluded: true},
158 this.games = this.games.concat(response.games.map(g => {
159 const type = this.classifyObject(g);
160 const vname = this.getVname(g.vid);
161 return Object.assign({}, g, {type: type, vname: vname});
165 // Also ask for corr challenges (open + sent to me)
169 {uid: this.st.user.id},
171 // Gather all senders names, and then retrieve full identity:
172 // (TODO [perf]: some might be online...)
173 const uids = response.challenges.map(c => { return c.uid });
176 { ids: uids.join(",") },
179 response2.users.forEach(u => {names[u.id] = u.name});
180 this.challenges = this.challenges.concat(
181 response.challenges.map(c => {
182 // (just players names in fact)
183 const from = {name: names[c.uid], id: c.uid};
184 const type = this.classifyObject(c);
185 const vname = this.getVname(c.vid);
186 return Object.assign({}, c, {type: type, vname: vname, from: from});
193 // 0.1] Ask server for room composition:
194 const funcPollClients = () => {
195 // Same strategy as in Game.vue: send connection
196 // after we're sure WebSocket is initialized
197 this.st.conn.send(JSON.stringify({code:"connect"}));
198 this.st.conn.send(JSON.stringify({code:"pollclients"}));
200 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
202 else //socket not ready yet (initial loading)
203 this.st.conn.onopen = funcPollClients;
204 this.st.conn.onmessage = this.socketMessageListener;
205 const socketCloseListener = () => {
206 store.socketCloseListener(); //reinitialize connexion (in store.js)
207 this.st.conn.addEventListener('message', this.socketMessageListener);
208 this.st.conn.addEventListener('close', socketCloseListener);
210 this.st.conn.onclose = socketCloseListener;
212 mounted: function() {
213 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
214 .forEach(elt => elt.addEventListener("click", processModalClick));
215 document.querySelectorAll("#predefinedTimeControls > button").forEach(
216 (b) => { b.addEventListener("click",
217 () => { this.newchallenge.timeControl = b.innerHTML; }
223 filterChallenges: function(type) {
224 return this.challenges.filter(c => c.type == type);
226 filterGames: function(type) {
227 return this.games.filter(g => g.type == type);
229 classifyObject: function(o) { //challenge or game
230 // Heuristic: should work for most cases... (TODO)
231 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
233 showGame: function(g) {
234 // NOTE: we are an observer, since only games I don't play are shown here
235 // ==> Moves sent by connected remote player(s) if live game
236 let url = "/game/" + g.id;
237 if (g.type == "live")
238 url += "?rid=" + g.rid;
239 this.$router.push(url);
241 setDisplay: function(letter, type, e) {
242 this[letter + "display"] = type;
243 e.target.classList.add("active");
244 if (!!e.target.previousElementSibling)
245 e.target.previousElementSibling.classList.remove("active");
247 e.target.nextElementSibling.classList.remove("active");
249 getVname: function(vid) {
250 const variant = this.st.variants.find(v => v.id == vid);
251 // this.st.variants might be uninitialized (variant == null)
252 return (!!variant ? variant.name : "");
254 whatPlayerDoes: function(p) {
255 if (this.games.some(g => g.type == "live"
256 && g.players.some(pl => pl.sid == p.sid)))
260 return "Challenge"; //player is available
262 sendSomethingTo: function(to, code, obj, warnDisconnected) {
263 const doSend = (code, obj, sid) => {
264 this.st.conn.send(JSON.stringify(Object.assign(
272 // Challenge with targeted players
274 Object.keys(this.people).find(sid => this.people[sid].name == to);
277 if (!!warnDisconnected)
278 alert(this.st.tr["Warning: target is not connected"]);
282 doSend(code, obj, targetSid);
286 // Open challenge: send to all connected players (me excepted)
287 Object.keys(this.people).forEach(sid => {
288 if (sid != this.st.user.sid)
289 doSend(code, obj, sid);
295 socketMessageListener: function(msg) {
296 const data = JSON.parse(msg.data);
300 alert(this.st.tr["Warning: multi-tabs not supported"]);
302 // 0.2] Receive clients list (just socket IDs)
305 data.sockIds.forEach(sid => {
306 this.$set(this.people, sid, {id:0, name:""});
307 // Ask identity, challenges and game(s)
308 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
309 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
311 // Also ask current games to all playing peers (TODO: some design issue)
312 this.st.conn.send(JSON.stringify({code:"askgames"}));
317 // Request for identification: reply if I'm not anonymous
318 if (this.st.user.id > 0)
320 this.st.conn.send(JSON.stringify({code:"identity",
322 // NOTE: decompose to avoid revealing email
323 name: this.st.user.name,
324 sid: this.st.user.sid,
333 this.$set(this.people, data.user.sid,
334 {id: data.user.id, name: data.user.name});
339 // Send my current live challenge (if any)
340 const cIdx = this.challenges.findIndex(c =>
341 c.from.sid == this.st.user.sid && c.type == "live");
344 const c = this.challenges[cIdx];
347 // Only share targeted challenges to the targets:
348 const toSid = Object.keys(this.people).find(k =>
349 this.people[k].name == c.to);
350 if (toSid != data.from)
355 // Minimal challenge informations: (from not required)
360 timeControl: c.timeControl,
362 this.st.conn.send(JSON.stringify({code:"challenge",
363 chall:myChallenge, target:data.from}));
369 // Receive challenge from some player (+sid)
370 let newChall = data.chall;
371 newChall.type = this.classifyObject(data.chall);
373 Object.assign({sid:data.from}, this.people[data.from]);
374 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
375 newChall.vname = this.getVname(newChall.vid);
376 this.challenges.push(newChall);
381 // Receive game from some player (+sid)
382 // NOTE: it may be correspondance (if newgame while we are connected)
383 // If duplicate found: select rid (remote ID) at random
384 let game = this.games.find(g => g.id == data.game.id);
385 if (!!game && Math.random() < 0.5)
386 game.rid = data.from;
389 let newGame = data.game;
390 newGame.type = this.classifyObject(data.game);
391 newGame.vname = this.getVname(data.game.vid);
392 newGame.rid = data.from;
394 this.games.push(newGame);
400 // TODO: next line required ?!
401 //ArrayFun.remove(this.challenges, c => c.id == data.cid);
402 // New game just started: data contain all information
403 if (this.classifyObject(data.gameInfo) == "live")
404 this.startNewGame(data.gameInfo);
407 this.infoMessage = "New game started: " +
408 "<a href='#/game/" + data.gameInfo.id + "'>" +
409 "#/game/" + data.gameInfo.id + "</a>";
410 let modalBox = document.getElementById("modalInfo");
411 modalBox.checked = true;
412 setTimeout(() => { modalBox.checked = false; }, 3000);
416 case "refusechallenge":
418 ArrayFun.remove(this.challenges, c => c.id == data.cid);
419 localStorage.removeItem("challenge");
420 alert(this.st.tr["Challenge declined"]);
423 case "deletechallenge":
425 // NOTE: the challenge may be already removed
426 ArrayFun.remove(this.challenges, c => c.id == data.cid);
427 localStorage.removeItem("challenge"); //in case of
432 this.$set(this.people, data.from, {name:"", id:0});
433 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
434 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
435 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
440 this.$delete(this.people, data.from);
441 // Also remove all challenges sent by this player:
442 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
443 // And all live games where he plays and no other opponent is online
444 ArrayFun.remove(this.games, g =>
445 g.type == "live" && (g.players.every(p => p.sid == data.from
446 || !this.people[p.sid])), "all");
451 // Challenge lifecycle:
452 tryChallenge: function(player) {
454 return; //anonymous players cannot be challenged
455 this.newchallenge.to = player.name;
456 doClick("modalNewgame");
458 challOrWatch: function(p, e) {
459 switch (e.target.innerHTML)
462 this.tryChallenge(p);
465 // NOTE: this search for game was already done for rendering
466 this.showGame(this.games.find(
467 g => g.type=="live" && g.players.some(pl => pl.sid == p.sid)));
471 newChallenge: async function() {
472 if (this.newchallenge.vid == "")
473 return alert(this.st.tr["Please select a variant"]);
474 const vname = this.getVname(this.newchallenge.vid);
475 const vModule = await import("@/variants/" + vname + ".js");
476 window.V = vModule.VariantRules;
477 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
478 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
479 const error = checkChallenge(this.newchallenge);
482 const ctype = this.classifyObject(this.newchallenge);
483 if (ctype == "corr" && this.st.user.id <= 0)
484 return alert(this.st.tr["Please log in to play correspondance games"]);
485 // NOTE: "from" information is not required here
486 let chall = Object.assign({}, this.newchallenge);
487 const finishAddChallenge = (cid,warnDisconnected) => {
488 chall.id = cid || "c" + getRandString();
489 // Send challenge to peers (if connected)
490 const isSent = this.sendSomethingTo(chall.to, "challenge",
491 {chall:chall}, !!warnDisconnected);
494 // Remove old challenge if any (only one at a time):
495 const cIdx = this.challenges.findIndex(c =>
496 c.from.sid == this.st.user.sid && c.type == ctype);
499 // Delete current challenge (will be replaced now)
500 this.sendSomethingTo(this.challenges[cIdx].to,
501 "deletechallenge", {cid:this.challenges[cIdx].id});
507 {id: this.challenges[cIdx].id}
510 this.challenges.splice(cIdx, 1);
512 // Add new challenge:
513 chall.added = Date.now();
514 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
517 chall.from = { //decompose to avoid revealing email
518 sid: this.st.user.sid,
520 name: this.st.user.name,
522 this.challenges.push(chall);
524 localStorage.setItem("challenge", JSON.stringify(chall));
525 // Also remember timeControl + vid for quicker further challenges:
526 localStorage.setItem("timeControl", chall.timeControl);
527 localStorage.setItem("vid", chall.vid);
528 document.getElementById("modalNewgame").checked = false;
532 // Live challenges have a random ID
533 finishAddChallenge(null, "warnDisconnected");
537 // Correspondance game: send challenge to server
542 response => { finishAddChallenge(response.cid); }
546 clickChallenge: function(c) {
547 const myChallenge = (c.from.sid == this.st.user.sid //live
548 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
551 if (c.type == "corr" && this.st.user.id <= 0)
552 return alert(this.st.tr["Please log in to accept corr challenges"]);
554 if (!!c.to) //c.to == this.st.user.name (connected)
556 // TODO: if special FEN, show diagram after loading variant
557 c.accepted = confirm("Accept challenge?");
561 c.seat = { //again, avoid c.seat = st.user to not reveal email
562 sid: this.st.user.sid,
564 name: this.st.user.name,
570 this.st.conn.send(JSON.stringify({
571 code: "refusechallenge",
572 cid: c.id, target: c.from.sid}));
574 // TODO: refactor the "sendSomethingTo()" function
576 this.sendSomethingTo(null, "deletechallenge", {cid:c.id});
579 this.st.conn.send(JSON.stringify({
580 code:"deletechallenge", target: c.from.sid, cid: c.id}));
585 if (c.type == "corr")
594 localStorage.removeItem("challenge");
595 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
597 // In all cases, the challenge is consumed:
598 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
600 // NOTE: when launching game, the challenge is already deleted
601 launchGame: async function(c) {
602 const vModule = await import("@/variants/" + c.vname + ".js");
603 window.V = vModule.VariantRules;
604 // These game informations will be sent to other players
608 fen: c.fen || V.GenRandInitFen(),
609 players: shuffle([c.from, c.seat]), //white then black
611 vname: c.vname, //theoretically vid is enough, but much easier with vname
612 timeControl: c.timeControl,
614 let oppsid = c.from.sid; //may not be defined if corr + offline opp
617 oppsid = Object.keys(this.people).find(sid =>
618 this.people[sid].id == c.from.id);
620 const tryNotifyOpponent = () => {
621 if (!!oppsid) //opponent is online
623 this.st.conn.send(JSON.stringify({code:"newgame",
624 gameInfo:gameInfo, target:oppsid, cid:c.id}));
627 if (c.type == "live")
629 // NOTE: in this case we are sure opponent is online
631 this.startNewGame(gameInfo);
633 else //corr: game only on server
638 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
640 gameInfo.id = response.gameId;
642 this.$router.push("/game/" + response.gameId);
646 // Send game info to everyone except opponent (and me)
647 Object.keys(this.people).forEach(sid => {
648 if (![this.st.user.sid,oppsid].includes(sid))
650 this.st.conn.send(JSON.stringify({code:"game",
651 game: { //minimal game info:
653 players: gameInfo.players,
655 timeControl: gameInfo.timeControl,
661 // NOTE: for live games only (corr games start on the server)
662 startNewGame: function(gameInfo) {
663 const game = Object.assign({}, gameInfo, {
664 // (other) Game infos: constant
665 fenStart: gameInfo.fen,
667 // Game state (including FEN): will be updated
669 clocks: [-1, -1], //-1 = unstarted
670 initime: [0, 0], //initialized later
673 GameStorage.add(game);
674 if (this.st.settings.sound >= 1)
675 new Audio("/sounds/newgame.mp3").play().catch(err => {});
676 this.$router.push("/game/" + gameInfo.id);
682 <style lang="sass" scoped>
687 margin: 10px auto 5px auto
698 @media screen and (max-width: 767px)