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["Cadence"] }} *
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="sid in Object.keys(people)" v-if="!!people[sid].name")
54 span {{ people[sid].name }}
56 v-if="people[sid].name != st.user.name"
57 @click="challOrWatch(sid, $event)"
59 | {{ st.tr[!!people[sid].gamer ? 'Playing' : 'Available'] }}
60 p.anonymous @nonymous ({{ anonymousCount }})
62 Chat(:newChat="newChat" @mychat="processChat")
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") || "",
115 // st.variants changes only once, at loading from [] to [...]
116 "st.variants": function(variantArray) {
117 // Set potential challenges and games variant names:
118 this.challenges.forEach(c => {
120 c.vname = this.getVname(c.vid);
122 this.games.forEach(g => {
124 g.vname = this.getVname(g.vid);
129 anonymousCount: function() {
131 Object.values(this.people).forEach(p => { count += (!p.name ? 1 : 0); });
135 created: function() {
136 // Always add myself to players' list
137 const my = this.st.user;
138 this.$set(this.people, my.sid, {id:my.id, name:my.name});
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 by/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...)
161 response.challenges.forEach(c => {
162 if (c.uid != this.st.user.id)
163 names[c.uid] = ""; //unknwon for now
164 else if (!!c.target && c.target != this.st.user.id)
165 names[c.target] = "";
167 const addChallenges = (newChalls) => {
168 names[this.st.user.id] = this.st.user.name; //in case of
169 this.challenges = this.challenges.concat(
170 response.challenges.map(c => {
171 const from = {name: names[c.uid], id: c.uid}; //or just name
172 const type = this.classifyObject(c);
173 const vname = this.getVname(c.vid);
174 return Object.assign({},
179 to: (!!c.target ? names[c.target] : ""),
189 { ids: Object.keys(names).join(",") },
191 response2.users.forEach(u => {names[u.id] = u.name});
200 // 0.1] Ask server for room composition:
201 const funcPollClients = () => {
202 // Same strategy as in Game.vue: send connection
203 // after we're sure WebSocket is initialized
204 this.st.conn.send(JSON.stringify({code:"connect"}));
205 this.st.conn.send(JSON.stringify({code:"pollclients"}));
206 this.st.conn.send(JSON.stringify({code:"pollgamers"}));
208 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
210 else //socket not ready yet (initial loading)
211 this.st.conn.onopen = funcPollClients;
212 this.st.conn.onmessage = this.socketMessageListener;
213 const socketCloseListener = () => {
214 store.socketCloseListener(); //reinitialize connexion (in store.js)
215 this.st.conn.addEventListener('message', this.socketMessageListener);
216 this.st.conn.addEventListener('close', socketCloseListener);
218 this.st.conn.onclose = socketCloseListener;
220 mounted: function() {
221 [document.getElementById("infoDiv"),document.getElementById("newgameDiv")]
222 .forEach(elt => elt.addEventListener("click", processModalClick));
223 document.querySelectorAll("#predefinedTimeControls > button").forEach(
224 (b) => { b.addEventListener("click",
225 () => { this.newchallenge.timeControl = b.innerHTML; }
231 filterChallenges: function(type) {
232 return this.challenges.filter(c => c.type == type);
234 filterGames: function(type) {
235 return this.games.filter(g => g.type == type);
237 classifyObject: function(o) { //challenge or game
238 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
240 showGame: function(g) {
241 // NOTE: we are an observer, since only games I don't play are shown here
242 // ==> Moves sent by connected remote player(s) if live game
243 let url = "/game/" + g.id;
244 if (g.type == "live")
245 url += "?rid=" + g.rid;
246 this.$router.push(url);
248 setDisplay: function(letter, type, e) {
249 this[letter + "display"] = type;
250 e.target.classList.add("active");
251 if (!!e.target.previousElementSibling)
252 e.target.previousElementSibling.classList.remove("active");
254 e.target.nextElementSibling.classList.remove("active");
256 getVname: function(vid) {
257 const variant = this.st.variants.find(v => v.id == vid);
258 // this.st.variants might be uninitialized (variant == null)
259 return (!!variant ? variant.name : "");
261 processChat: function(chat) {
262 // When received on server, this will trigger a "notifyRoom"
263 this.st.conn.send(JSON.stringify({code:"newchat", chat: chat}));
265 sendSomethingTo: function(to, code, obj, warnDisconnected) {
266 const doSend = (code, obj, sid) => {
267 this.st.conn.send(JSON.stringify(Object.assign(
273 if (!to || (!to.sid && !to.name))
275 // Open challenge: send to all connected players (me excepted)
276 Object.keys(this.people).forEach(sid => {
277 if (sid != this.st.user.sid)
278 doSend(code, obj, sid);
288 if (to.name == this.st.user.name)
289 return alert(this.st.tr["Cannot challenge self"]);
290 // Challenge with targeted players
292 Object.keys(this.people).find(sid => this.people[sid].name == to.name);
295 if (!!warnDisconnected)
296 alert(this.st.tr["Warning: target is not connected"]);
300 doSend(code, obj, targetSid);
305 socketMessageListener: function(msg) {
306 const data = JSON.parse(msg.data);
310 this.st.conn.send(JSON.stringify({code:"duplicate", page:"/"}));
311 this.st.conn.send = () => {};
312 alert(this.st.tr["Warning: multi-tabs not supported"]);
314 // 0.2] Receive clients list (just socket IDs)
316 data.sockIds.forEach(sid => {
317 this.$set(this.people, sid, {id:0, name:""});
318 // Ask identity and challenges
319 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
320 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
324 // NOTE: we could make a difference between people in hall
325 // and gamers, but is it necessary?
326 data.sockIds.forEach(sid => {
327 this.$set(this.people, sid, {id:0, name:"", gamer:true});
328 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
330 // Also ask current games to all playing peers (TODO: some design issue)
331 this.st.conn.send(JSON.stringify({code:"askgames"}));
334 // Request for identification: reply if I'm not anonymous
335 if (this.st.user.id > 0)
337 this.st.conn.send(JSON.stringify({code:"identity",
339 // NOTE: decompose to avoid revealing email
340 name: this.st.user.name,
341 sid: this.st.user.sid,
348 this.$set(this.people, data.user.sid,
351 name: data.user.name,
352 gamer: this.people[data.user.sid].gamer,
357 // Send my current live challenge (if any)
358 const cIdx = this.challenges.findIndex(c =>
359 c.from.sid == this.st.user.sid && c.type == "live");
362 const c = this.challenges[cIdx];
363 // TODO: code below requires "c.to" to have given his identity,
364 // but it can happen that the identity arrives later, which
365 // prevent him from receiving the challenge.
366 // ==> Filter later (when receiving challenge)
369 // // Only share targeted challenges to the targets:
370 // const toSid = Object.keys(this.people).find(k =>
371 // this.people[k].name == c.to);
372 // if (toSid != data.from)
377 // Minimal challenge informations: (from not required)
382 timeControl: c.timeControl,
385 this.st.conn.send(JSON.stringify({code:"challenge",
386 chall:myChallenge, target:data.from}));
391 // Receive challenge from some player (+sid)
392 // NOTE about next condition: see "askchallenge" case.
393 if (!data.chall.to || data.chall.to == this.st.user.name)
395 let newChall = data.chall;
396 newChall.type = this.classifyObject(data.chall);
398 Object.assign({sid:data.from}, this.people[data.from]);
399 newChall.vname = this.getVname(newChall.vid);
400 this.challenges.push(newChall);
405 // Receive game from some player (+sid)
406 // NOTE: it may be correspondance (if newgame while we are connected)
407 // If duplicate found: select rid (remote ID) at random
408 let game = this.games.find(g => g.id == data.game.id);
411 if (Math.random() < 0.5)
412 game.rid = data.from;
416 let newGame = data.game;
417 newGame.type = this.classifyObject(data.game);
418 newGame.vname = this.getVname(data.game.vid);
419 newGame.rid = data.from;
420 if (!data.game.score)
422 this.games.push(newGame);
427 // New game just started: data contain all information
428 if (this.classifyObject(data.gameInfo) == "live")
429 this.startNewGame(data.gameInfo);
432 this.infoMessage = "New game started: " +
433 "<a href='#/game/" + data.gameInfo.id + "'>" +
434 "#/game/" + data.gameInfo.id + "</a>";
435 let modalBox = document.getElementById("modalInfo");
436 modalBox.checked = true;
437 setTimeout(() => { modalBox.checked = false; }, 3000);
441 this.newChat = data.chat;
443 case "refusechallenge":
444 ArrayFun.remove(this.challenges, c => c.id == data.cid);
445 alert(this.st.tr["Challenge declined"]);
447 case "deletechallenge":
448 // NOTE: the challenge may be already removed
449 ArrayFun.remove(this.challenges, c => c.id == data.cid);
453 this.$set(this.people, data.from, {name:"", id:0, gamer:data.code[0]=='g'});
454 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
455 if (data.code == "connect")
456 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.from}));
458 this.st.conn.send(JSON.stringify({code:"askgame", target:data.from}));
462 this.$delete(this.people, data.from);
463 if (data.code == "disconnect")
465 // Also remove all challenges sent by this player:
466 ArrayFun.remove(this.challenges, c => c.from.sid == data.from);
470 // And all live games where he plays and no other opponent is online
471 ArrayFun.remove(this.games, g =>
472 g.type == "live" && (g.players.every(p => p.sid == data.from
473 || !this.people[p.sid])), "all");
478 // Challenge lifecycle:
479 tryChallenge: function(sid) {
480 if (this.people[sid].id == 0)
481 return; //anonymous players cannot be challenged
482 // TODO: SID is available, so we could use it instead of searching from name
483 this.newchallenge.to = this.people[sid].name;
484 doClick("modalNewgame");
486 challOrWatch: function(sid) {
487 if (!this.people[sid].gamer)
489 // Available, in Hall
490 this.tryChallenge(sid);
495 this.showGame(this.games.find(
496 g => g.players.some(pl => pl.sid == sid || pl.uid == this.people[sid].id)));
499 newChallenge: async function() {
500 if (this.newchallenge.vid == "")
501 return alert(this.st.tr["Please select a variant"]);
502 if (!!this.newchallenge.to && this.newchallenge.to == this.st.user.name)
503 return alert(this.st.tr["Self-challenge is forbidden"]);
504 const vname = this.getVname(this.newchallenge.vid);
505 const vModule = await import("@/variants/" + vname + ".js");
506 window.V = vModule.VariantRules;
507 if (!!this.newchallenge.timeControl.match(/^[0-9]+$/))
508 this.newchallenge.timeControl += "+0"; //assume minutes, no increment
509 const error = checkChallenge(this.newchallenge);
512 const ctype = this.classifyObject(this.newchallenge);
513 if (ctype == "corr" && this.st.user.id <= 0)
514 return alert(this.st.tr["Please log in to play correspondance games"]);
515 // NOTE: "from" information is not required here
516 let chall = Object.assign({}, this.newchallenge);
517 const finishAddChallenge = (cid,warnDisconnected) => {
518 chall.id = cid || "c" + getRandString();
519 // Send challenge to peers (if connected)
520 const isSent = this.sendSomethingTo({name:chall.to}, "challenge",
521 {chall:chall}, !!warnDisconnected);
524 // Remove old challenge if any (only one at a time of a given type):
525 const cIdx = this.challenges.findIndex(c =>
526 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) && c.type == ctype);
529 // Delete current challenge (will be replaced now)
530 this.sendSomethingTo({name:this.challenges[cIdx].to},
531 "deletechallenge", {cid:this.challenges[cIdx].id});
537 {id: this.challenges[cIdx].id}
540 this.challenges.splice(cIdx, 1);
542 // Add new challenge:
543 chall.added = Date.now();
544 // NOTE: vname and type are redundant (can be deduced from timeControl + vid)
547 chall.from = { //decompose to avoid revealing email
548 sid: this.st.user.sid,
550 name: this.st.user.name,
552 this.challenges.push(chall);
553 // Remember timeControl + vid for quicker further challenges:
554 localStorage.setItem("timeControl", chall.timeControl);
555 localStorage.setItem("vid", chall.vid);
556 document.getElementById("modalNewgame").checked = false;
560 // Live challenges have a random ID
561 finishAddChallenge(null, "warnDisconnected");
565 // Correspondance game: send challenge to server
570 response => { finishAddChallenge(response.cid); }
574 clickChallenge: function(c) {
575 const myChallenge = (c.from.sid == this.st.user.sid //live
576 || (this.st.user.id > 0 && c.from.id == this.st.user.id)); //corr
579 if (c.type == "corr" && this.st.user.id <= 0)
580 return alert(this.st.tr["Please log in to accept corr challenges"]);
582 if (!!c.to) //c.to == this.st.user.name (connected)
584 // TODO: if special FEN, show diagram after loading variant
585 c.accepted = confirm("Accept challenge?");
589 c.seat = { //again, avoid c.seat = st.user to not reveal email
590 sid: this.st.user.sid,
592 name: this.st.user.name,
598 this.st.conn.send(JSON.stringify({
599 code: "refusechallenge",
600 cid: c.id, target: c.from.sid}));
602 this.sendSomethingTo(!!c.to ? {sid:c.from.sid} : null, "deletechallenge", {cid:c.id});
606 if (c.type == "corr")
614 this.sendSomethingTo({name:c.to}, "deletechallenge", {cid:c.id});
616 // In all cases, the challenge is consumed:
617 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
619 // NOTE: when launching game, the challenge is already being deleted
620 launchGame: async function(c) {
621 const vModule = await import("@/variants/" + c.vname + ".js");
622 window.V = vModule.VariantRules;
623 // These game informations will be sent to other players
627 fen: c.fen || V.GenRandInitFen(),
628 players: shuffle([c.from, c.seat]), //white then black
630 vname: c.vname, //theoretically vid is enough, but much easier with vname
631 timeControl: c.timeControl,
633 let oppsid = c.from.sid; //may not be defined if corr + offline opp
636 oppsid = Object.keys(this.people).find(sid =>
637 this.people[sid].id == c.from.id);
639 const tryNotifyOpponent = () => {
640 if (!!oppsid) //opponent is online
642 this.st.conn.send(JSON.stringify({code:"newgame",
643 gameInfo:gameInfo, target:oppsid, cid:c.id}));
646 if (c.type == "live")
648 // NOTE: in this case we are sure opponent is online
650 this.startNewGame(gameInfo);
652 else //corr: game only on server
657 {gameInfo: gameInfo, cid: c.id}, //cid useful to delete challenge
659 gameInfo.id = response.gameId;
661 this.$router.push("/game/" + response.gameId);
665 // Send game info to everyone except opponent (and me)
666 Object.keys(this.people).forEach(sid => {
667 if (![this.st.user.sid,oppsid].includes(sid))
669 this.st.conn.send(JSON.stringify({code:"game",
670 game: { //minimal game info:
672 players: gameInfo.players,
674 timeControl: gameInfo.timeControl,
680 // NOTE: for live games only (corr games start on the server)
681 startNewGame: function(gameInfo) {
682 const game = Object.assign({}, gameInfo, {
683 // (other) Game infos: constant
684 fenStart: gameInfo.fen,
686 // Game state (including FEN): will be updated
688 clocks: [-1, -1], //-1 = unstarted
689 initime: [0, 0], //initialized later
692 GameStorage.add(game);
693 if (this.st.settings.sound >= 1)
694 new Audio("/sounds/newgame.mp3").play().catch(err => {});
695 this.$router.push("/game/" + gameInfo.id);
701 <style lang="sass" scoped>
706 margin: 10px auto 5px auto
717 @media screen and (max-width: 767px)