3 input#modalNewgame.modal(type="checkbox")
4 div(role="dialog" aria-labelledby="titleFenedit")
6 label#closeNewgame.modal-close(for="modalNewgame")
8 label(for="selectVariant") {{ st.tr["Variant"] }}
9 select#selectVariant(v-model="newchallenge.vid")
10 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
12 label(for="selectNbPlayers") {{ st.tr["Number of players"] }}
13 select#selectNbPlayers(v-model="newchallenge.nbPlayers")
14 option(v-show="possibleNbplayers(2)" value="2" selected) 2
15 option(v-show="possibleNbplayers(3)" value="3") 3
16 option(v-show="possibleNbplayers(4)" value="4") 4
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)"] }}
24 input(type="text" v-model="newchallenge.to[0]")
25 input(v-show="newchallenge.nbPlayers>=3" type="text"
26 v-model="newchallenge.to[1]")
27 input(v-show="newchallenge.nbPlayers==4" type="text"
28 v-model="newchallenge.to[2]")
29 fieldset(v-if="st.user.id > 0")
30 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
31 input#inputFen(type="text" v-model="newchallenge.fen")
32 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
34 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
35 button(onClick="doClick('modalNewgame')") New game
37 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
39 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
40 label(for="challengeSection" aria-hidden="true") Challenges
43 button(@click="cdisplay='live'") Live Challenges
44 button(@click="cdisplay='corr'") Correspondance challenges
45 ChallengeList(v-show="cdisplay=='live'"
46 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
47 ChallengeList(v-show="cdisplay=='corr'"
48 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
49 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
50 label(for="peopleSection" aria-hidden="true") People
53 button(@click="pdisplay='players'") Players
54 button(@click="pdisplay='chat'") Chat
55 #players(v-show="pdisplay=='players'")
57 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
58 :class="{anonymous: !!p.count}"
60 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
61 #chat(v-show="pdisplay=='chat'")
63 input#gameSection(type="radio" aria-hidden="true" name="accordion")
64 label(for="gameSection" aria-hidden="true") Games
67 button(@click="gdisplay='live'") Live games
68 button(@click="gdisplay='corr'") Correspondance games
69 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
70 @show-game="showGame")
71 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
72 @show-game="showGame")
76 import { store } from "@/store";
77 import { NbPlayers } from "@/data/nbPlayers";
78 import { checkChallenge } from "@/data/challengeCheck";
79 import { ArrayFun } from "@/utils/array";
80 import { ajax } from "@/utils/ajax";
81 import { getRandString } from "@/utils/alea";
82 import GameList from "@/components/GameList.vue";
83 import ChallengeList from "@/components/ChallengeList.vue";
93 cdisplay: "live", //or corr
94 pdisplay: "players", //or chat
98 players: [], //online players (rename into "people" ?)
103 to: ["", "", ""], //name(s) of challenged player(s)
104 timeControl: "", //"2m+2s" ...etc
109 uniquePlayers: function() {
110 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
111 let anonymous = {id:0, name:"@nonymous", count:0};
113 this.players.forEach(p => {
119 if (anonymous.count > 0)
120 playerList.push(anonymous);
124 created: function() {
125 // Always add myself to players' list
126 this.players.push(this.st.user);
127 if (this.st.user.id > 0)
129 // Ask server for current corr games (all but mines)
133 // {excluded: this.st.user.id},
135 // this.games = this.games.concat(response.games);
138 // Also ask for corr challenges (open + sent to me)
142 {uid: this.st.user.id},
144 console.log(response.challenges);
145 // TODO: post-treatment on challenges ?
146 this.challenges = this.challenges.concat(response.challenges);
150 // 0.1] Ask server for room composition:
151 const socketOpenListener = () => {
152 this.st.conn.send(JSON.stringify({code:"pollclients"}));
154 this.st.conn.onopen = socketOpenListener;
155 // TODO: is this required here?
156 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
157 this.st.conn.onmessage = this.socketMessageListener;
158 const oldOnclose = this.st.conn.onclose;
159 const socketCloseListener = () => {
160 oldOnclose(); //reinitialize connexion (in store.js)
161 this.st.conn.addEventListener('message', this.socketMessageListener);
162 this.st.conn.addEventListener('close', socketCloseListener);
164 this.st.conn.onclose = socketCloseListener;
168 filterChallenges: function(type) {
169 return this.challenges.filter(c => c.type == type);
171 filterGames: function(type) {
172 return this.games.filter(c => c.type == type);
174 classifyObject: function(o) { //challenge or game
175 // Heuristic: should work for most cases... (TODO)
176 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
178 possibleNbplayers: function(nbp) {
179 if (this.newchallenge.vid == 0)
181 const idxInVariants =
182 this.st.variants.findIndex(v => v.id == this.newchallenge.vid);
183 return NbPlayers[this.st.variants[idxInVariants].name].includes(nbp);
185 showGame: function(g) {
186 // NOTE: we are an observer, since only games I don't play are shown here
187 // ==> Moves sent by connected remote player(s) if live game
188 let url = "/" + g.id;
189 if (g.type == "live")
191 const sids = g.players.map(p => p.sid).join(",");
192 url += "?sids=" + sids;
194 this.$router.push(url);
196 getVname: function(vid) {
197 const vIdx = this.st.variants.findIndex(v => v.id == vid);
198 return this.st.variants[vIdx].name;
200 getSid: function(pname) {
201 const pIdx = this.players.findIndex(pl => pl.name == pname);
202 return (pIdx === -1 ? null : this.players[pIdx].sid);
204 getPname: function(sid) {
205 const pIdx = this.players.findIndex(pl => pl.sid == sid);
206 return (pIdx === -1 ? null : this.players[pIdx].name);
208 sendSomethingTo: function(to, code, obj, warnDisconnected) {
209 const doSend = (code, obj, sid) => {
210 this.st.conn.send(JSON.stringify(Object.assign(
219 to.forEach(pname => {
220 // Challenge with targeted players
221 const targetSid = this.getSid(pname);
224 if (!!warnDisconnected)
225 alert("Warning: " + pname + " is not connected");
228 doSend(code, obj, targetSid);
233 // Open challenge: send to all connected players (except us)
234 this.players.forEach(p => {
235 if (p.sid != this.st.user.sid) //only sid is always set
236 doSend(code, obj, p.sid);
241 socketMessageListener: function(msg) {
242 // Save and call current st.conn.onmessage if one was already defined
243 // --> also needed in future Game.vue (also in Chat.vue component)
244 this.oldOnmessage(msg);
245 const data = JSON.parse(msg.data);
248 // 0.2] Receive clients list (just socket IDs)
251 data.sockIds.forEach(sid => {
252 this.players.push({sid:sid, id:0, name:""});
253 // Ask identity, challenges and game(s)
254 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
255 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
256 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
262 // Request for identification: reply if I'm not anonymous
263 if (this.st.user.id > 0)
265 this.st.conn.send(JSON.stringify(
266 {code:"identity", user:this.st.user, target:data.from}));
272 // Send my current live challenge (if any)
273 const cIdx = this.challenges
274 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
277 const c = this.challenges[cIdx];
280 // Minimal challenge informations: (from not required)
285 timeControl: c.timeControl
287 this.st.conn.send(JSON.stringify({code:"challenge",
288 challenge:myChallenge, target:data.from}));
294 // Send my current live game (if any)
295 if (!!localStorage["gid"])
299 // Minimal game informations: (fen+clock not required)
300 id: localStorage["gid"],
301 players: JSON.parse(localStorage["players"]), //array sid+id+name
302 vname: localStorage["vname"],
303 timeControl: localStorage["timeControl"],
305 this.st.conn.send(JSON.stringify({code:"game",
306 game:myGame, target:data.from}));
312 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
313 this.players[pIdx].id = data.user.id;
314 this.players[pIdx].name = data.user.name;
319 // Receive challenge from some player (+sid)
320 let newChall = data.chall;
321 newChall.type = this.classifyObject(data.chall);
322 const pIdx = this.players.findIndex(p => p.sid == data.from);
323 newChall.from = this.players[pIdx]; //may be anonymous
324 newChall.added = Date.now();
325 newChall.vname = this.getVname(newChall.vid);
326 this.challenges.push(newChall);
331 // Receive game from some player (+sid)
332 // NOTE: it may be correspondance (if newgame while we are connected)
333 let newGame = data.game;
334 newGame.type = this.classifyObject(data.game);
335 newGame.vname = newGame.vname;
336 this.games.push(newGame);
339 // * - receive "new game": if live, store locally + redirect to game
340 // * If corr: notify "new game has started", give link, but do not redirect
343 // Delete corresponding challenge:
344 ArrayFun.remove(this.challenges, c => c.id == data.cid);
345 // New game just started: data contain all informations
346 this.newGame(data.gameInfo);
349 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
350 // NOTE: challenge "socket" actions accept+withdraw only for live challenges
351 case "acceptchallenge":
353 // Someone accept an open (or targeted) challenge
354 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
355 let c = this.challenges[cIdx];
357 c.seats = [...Array(c.to.length)];
358 const pIdx = this.players.findIndex(p => p.sid == data.from);
359 // Put this player in the first empty seat we find:
361 for (; sIdx<c.seats.length; sIdx++)
365 c.seats[sIdx] = this.players[pIdx];
369 if (sIdx == c.seats.length - 1)
371 // All seats are taken: game can start
376 case "withdrawchallenge":
378 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
379 let seats = this.challenges[cIdx].seats;
380 const sIdx = seats.findIndex(s => s.sid == data.sid);
381 seats[sIdx] = undefined;
384 case "refusechallenge":
386 alert(this.getPname(data.from) + " refused your challenge");
387 ArrayFun.remove(this.challenges, c => c.id == data.cid);
390 case "deletechallenge":
392 ArrayFun.remove(this.challenges, c => c.id == data.cid);
397 this.players.push({name:"", id:0, sid:data.sid});
398 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
399 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
400 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
405 ArrayFun.remove(this.players, p => p.sid == data.sid);
406 // Also remove all challenges sent by this player:
407 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
408 // And all live games where he plays and no other opponent is online
409 ArrayFun.remove(this.games, g =>
410 g.type == "live" && (g.players.every(p => p.sid == data.sid
411 || !this.players.some(pl => pl.sid == p.sid))), "all");
416 // Challenge lifecycle:
417 tryChallenge: function(player) {
419 return; //anonymous players cannot be challenged
420 this.newchallenge.to[0] = player.name;
421 doClick("modalNewgame");
423 newChallenge: async function() {
424 const vname = this.getVname(this.newchallenge.vid);
425 const vModule = await import("@/variants/" + vname + ".js");
426 window.V = vModule.VariantRules;
427 const error = checkChallenge(this.newchallenge);
430 const ctype = this.classifyObject(this.newchallenge);
431 const cto = this.newchallenge.to.slice(0, this.newchallenge.nbPlayers - 1);
432 // NOTE: "from" information is not required here
435 fen: this.newchallenge.fen,
437 timeControl: this.newchallenge.timeControl,
438 vid: this.newchallenge.vid,
440 const finishAddChallenge = (cid,warnDisconnected) => {
441 chall.id = cid || "c" + getRandString();
442 // Send challenge to peers (if connected)
443 this.sendSomethingTo(cto, "challenge", {chall:chall}, !!warnDisconnected);
444 chall.added = Date.now();
447 chall.from = this.st.user;
448 this.challenges.push(chall);
449 document.getElementById("modalNewgame").checked = false;
451 const cIdx = this.challenges.findIndex(
452 c => c.from.sid == this.st.user.sid && c.type == ctype);
455 // Delete current challenge (will be replaced now)
456 this.sendSomethingTo(this.challenges[cIdx].to,
457 "deletechallenge", {cid:this.challenges[cIdx].id});
463 {id: this.challenges[cIdx].id}
466 this.challenges.splice(cIdx, 1);
470 // Live challenges have a random ID
471 finishAddChallenge(null, "warnDisconnected");
475 // Correspondance game: send challenge to server
480 response => { finishAddChallenge(response.cid); }
484 // * - accept challenge (corr or live) --> send info to challenge creator
485 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
486 // * - withdraw from challenge (if >= 3 players and previously accepted)
487 // * --> send info to challenge creator
488 // * - refuse challenge: send "refuse" to challenge sender, and "delete" to others
489 // * - prepare and start new game (if challenge is full after acceptation)
490 // * --> include challenge ID (so that opponents can delete the challenge too)
491 clickChallenge: function(c) {
493 console.log("click challenge");
498 this.st.conn.send(JSON.stringify({code: "withdrawchallenge",
499 cid: c.id, target: c.from.sid}));
500 if (c.type == "corr")
505 {action:"withdraw", id: this.challenges[cIdx].id}
510 else if (c.from.sid == this.st.user.sid
511 || (this.st.user.id > 0 && c.from.id == this.st.user.id))
513 // It's my challenge: cancel it
514 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
515 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
516 if (c.type == "corr")
521 {id: this.challenges[cIdx].id}
525 else //accept (or refuse) a challenge
530 // TODO: if special FEN, show diagram after loading variant
531 c.accepted = confirm("Accept challenge?");
533 this.st.conn.send(JSON.stringify({
534 code: (c.accepted ? "accept" : "refuse") + "challenge",
535 cid: c.id, target: c.from.sid}));
536 if (c.type == "corr" && c.accepted)
541 {action: "accept", id: this.challenges[cIdx].id}
546 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
547 if (c.type == "corr")
552 {id: this.challenges[cIdx].id}
558 // NOTE: for live games only (corr games are launched on server)
559 launchGame: async function(c) {
560 // Just assign colors and pass the message
561 const vname = this.getVname(c.vid);
562 const vModule = await import("@/variants/" + vname + ".js");
563 window.V = vModule.VariantRules;
564 let players = [c.from];
565 Array.prototype.push.apply(players, c.seats);
568 fen: c.fen || V.GenRandInitFen(),
569 // Players' names may be required if game start when a player is offline
570 players: players.map(p => { return {name:p.name, sid:p.sid} }),
572 timeControl: c.timeControl,
574 c.seats.forEach(s => {
575 // NOTE: cid required to remove challenge
576 this.st.conn.send(JSON.stringify({code:"newgame",
577 gameInfo:gameInfo, cid:c.id, target:s.sid}));
579 // Delete corresponding challenge:
580 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
581 this.newGame(gameInfo); //also!
583 // NOTE: for live games only (corr games are launched on server)
584 newGame: function(gameInfo) {
586 gameId: getRandString(),
587 vname: this.getVname(gameInfo.vid),
588 fenStart: gameInfo.fen,
589 players: gameInfo.players,
590 timeControl: gameInfo.timeControl,
592 if (this.st.settings.sound >= 1)
593 new Audio("/sounds/newgame.mp3").play().catch(err => {});
594 // TODO: redirect to game