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-5.col-md-offset-1.col-lg-4.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" checked aria-hidden="true" name="accordion")
50 label(for="peopleSection" aria-hidden="true") People
52 #players(v-show="pdisplay=='players'")
54 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
55 :class="{anonymous: !!p.count}"
57 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
58 #chat(v-show="pdisplay=='chat'")
60 input#gameSection(type="radio" checked aria-hidden="true" name="accordion")
61 label(for="gameSection" aria-hidden="true") Games
64 button(@click="gdisplay='live'") Live games
65 button(@click="gdisplay='corr'") Correspondance games
66 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
67 @show-game="showGame")
68 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
69 @show-game="showGame")
73 import { store } from "@/store";
74 import { NbPlayers } from "@/data/nbPlayers";
75 import { checkChallenge } from "@/data/challengeCheck";
76 import { ArrayFun } from "@/utils/array";
77 import { ajax } from "@/utils/ajax";
78 import { getRandString } from "@/utils/alea";
79 import GameList from "@/components/GameList.vue";
80 import ChallengeList from "@/components/ChallengeList.vue";
90 cdisplay: "live", //or corr
91 pdisplay: "players", //or chat
95 players: [], //online players
100 to: ["", "", ""], //name of challenged players
101 timeControl: "", //"2m+2s" ...etc
106 uniquePlayers: function() {
107 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
108 let anonymous = {id:0, name:"@nonymous", count:0};
110 this.players.forEach(p => {
116 if (anonymous.count > 0)
117 playerList.push(anonymous);
121 created: function() {
122 // Always add myself to players' list
123 this.players.push(this.st.user);
124 // Ask server for current corr games (all but mines)
132 // // Also ask for corr challenges (all)
140 // 0.1] Ask server for for room composition:
141 const socketOpenListener = () => {
142 this.st.conn.send(JSON.stringify({code:"pollclients"}));
144 this.st.conn.onopen = socketOpenListener;
145 // TODO: is this required here?
146 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
147 this.st.conn.onmessage = this.socketMessageListener;
148 const oldOnclose = this.st.conn.onclose;
149 const socketCloseListener = () => {
150 oldOnclose(); //reinitialize connexion (in store.js)
151 this.st.conn.addEventListener('message', this.socketMessageListener);
152 this.st.conn.addEventListener('close', socketCloseListener);
154 this.st.conn.onclose = socketCloseListener;
157 filterChallenges: function(type) {
158 return this.challenges.filter(c => c.type == type);
160 filterGames: function(type) {
161 return this.games.filter(c => c.type == type);
163 classifyChallenge: function(c) {
164 // Heuristic: should work for most cases... (TODO)
165 return (c.timeControl.indexOf('d') === -1 ? "live" : "corr");
167 socketMessageListener: function(msg) {
168 // Save and call current st.conn.onmessage if one was already defined
169 // --> also needed in future Game.vue (also in Chat.vue component)
170 this.oldOnmessage(msg);
171 const data = JSON.parse(msg.data);
174 // 0.2] Receive clients list (just socket IDs)
176 data.sockIds.forEach(sid => {
177 this.players.push({sid:sid, id:0, name:""});
178 // Ask identity, challenges and game(s)
179 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
180 this.st.conn.send(JSON.stringify({code:"askchallenges", target:sid}));
181 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
185 // Request for identification: reply if I'm not anonymous
186 if (this.st.user.id > 0)
188 this.st.conn.send(JSON.stringify(
189 {code:"identity", user:this.st.user, target:data.from}));
193 // Send my current live challenge (if any)
194 const cIdx = this.challenges
195 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
198 const c = this.challenges[cIdx];
201 // Minimal challenge informations: (from not required)
205 timeControl: c.timeControl
207 this.st.conn.send(JSON.stringify({code:"challenge",
208 challenge:myChallenge, target:data.from})
212 // TODO: Send my current live game (if any): variant, players, movesCount
215 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
216 this.players[pIdx].id = data.user.id;
217 this.players[pIdx].name = data.user.name;
220 // Receive challenge from some player (+sid)
221 let newChall = data.chall;
222 newChall.type = classifyChallenge(data.chall);
223 const pIdx = this.players.findIndex(p => p.sid == data.sid);
224 newChall.from = this.players[pIdx]; //may be anonymous
225 this.challenges.push(newChall);
228 // Receive game from some player (+sid)
229 // TODO: receive game summary (update, count moves)
230 // (just players names, time control, and ID + player ID)
231 // NOTE: it may be correspondance (if newgame while we are connected)
233 // * - receive "new game": if live, store locally + redirect to game
234 // * If corr: notify "new game has started", give link, but do not redirect
236 // TODO: new game just started: data contain all informations
237 // (id, players, time control, fenStart ...)
238 // + cid to remove challenge from list
240 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
241 case "acceptchallenge":
242 // someone accept an open (or targeted) challenge
243 // ==> if (open and) full and I don't play, delete from list
244 // If I play: just add player. Then, if full send a "newgame"
245 // and (if full) in any case, remove challenge from list.
246 if (this.challenges.some(c => c.id == data.cid) //.............TODO
247 this.newGame(data.challenge, data.user); //user.id et user.name
249 case "withdrawchallenge":
250 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
251 let chall = this.challenges[cIdx]
252 ArrayFun.remove(chall.players, p => p.id == data.uid);
253 chall.players.push({id:0, name:""});
255 case "cancelchallenge":
256 ArrayFun.remove(this.challenges, c => c.id == data.cid);
258 // TODO: distinguish hallConnect and gameConnect ?
259 // Or global variable players
260 // + game variable: "observers"
262 // * - receive "player connect": send our current challenge (to him or global)
263 // * Also send all our games (live - max 1 - and corr) [in web worker ?]
264 this.players.push({name:"", id:0, sid:data.sid});
265 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
267 // * - receive "player disconnect": remove from players list
269 ArrayFun.remove(this.players, p => p.sid == data.sid);
270 // TODO: also remove all challenges sent by this player,
271 // and all live games where he plays and no other opponent is online
275 showGame: function(game) {
276 // NOTE: if we are an observer, the game will be found in main games list
277 // (sent by connected remote players)
278 // TODO: game path ? /vname/gameId seems better
279 this.$router.push("/" + game.id);
281 tryChallenge: function(player) {
283 return; //anonymous players cannot be challenged
284 this.newchallenge.to[0] = player.name;
285 doClick("modalNewgame");
287 // * - accept challenge (corr or live) --> send info to all concerned players
288 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
289 // * - withdraw from challenge (if >= 3 players and previously accepted)
290 // * --> send info to all concerned players
291 // * - refuse challenge (or receive refusal): send to all challenge players (from + to)
292 // * except us ; graphics: modal again ? (inline ?)
293 // * - prepare and start new game (if challenge is full after acceptation)
294 // * --> include challenge ID (so that opponents can delete the challenge too)
295 // * Also send to all connected players (only from me)
296 clickChallenge: function(challenge) {
297 // TODO: also correspondance case (send to server)
298 const index = this.challenges.findIndex(c => c.id == challenge.id);
299 const toIdx = challenge.to.findIndex(name => name == this.st.user.name);
302 // It's a multiplayer challenge I accepted: withdraw
303 this.st.conn.send(JSON.stringify({code:"withdrawchallenge",
304 cid:challenge.id, user:this.st.user.sid}));
305 this.challenges.to.splice(toIdx, 1);
307 else if (challenge.from.id == user.id) //it's my challenge: cancel it
309 this.st.conn.send(JSON.stringify({code:"cancelchallenge", cid:challenge.id}));
310 this.challenges.splice(index, 1);
312 else //accept a challenge
314 this.st.conn.send(JSON.stringify({code:"acceptchallenge",
315 cid:challenge.id, user:me}));
316 this.challenges[index].to.push(me);
318 // TODO: accepter un challenge peut lancer une partie, il
319 // faut alors supprimer challenge + creer partie + la retourner et l'ajouter ici
320 // si pas le mien et FEN speciale :: (charger code variante et)
321 // montrer diagramme + couleur (orienté)
323 // user: last person to accept the challenge (TODO: revoir ça)
324 // newGame: function(chall, user) {
325 // const fen = chall.fen || V.GenRandInitFen();
326 // const game = {}; //TODO: fen, players, time ...
327 // //setStorage(game); //TODO
328 // game.players.forEach(p => { //...even if game is by corr (could be played live, why not...)
330 // JSON.stringify({code:"newgame", oppid:p.id, game:game}));
332 // if (this.settings.sound >= 1)
333 // new Audio("/sounds/newgame.mp3").play().catch(err => {});
335 // Load a variant file (TODO: should probably be global)
336 loadVariant: async function(vid, variantArray) {
337 const idxInVariants = variantArray.findIndex(v => v.id == vid);
338 const vname = variantArray[idxInVariants].name;
339 const vModule = await import("@/variants/" + vname + ".js");
340 window.V = vModule.VariantRules;
343 // Send new challenge (corr or live, cf. time control), with button or click on player
344 newChallenge: async function() {
345 // TODO: put this "load variant" block elsewhere
346 const vname = this.loadVariant(this.newchallenge.vid, this.st.variants);
347 // checkChallenge side-effect = , and mainTime + increment in seconds
348 // TODO: should not be a side-effect but set here ; for received server challenges we do not have mainTime+increment
349 const error = checkChallenge(this.newchallenge);
352 if (this.challenges.some(c => c.from.sid == this.st.user.sid && c.liveGame))
354 document.getElementById("modalNewgame").checked = false;
355 return alert("You already have a pending live challenge");
356 // TODO: better to just replace current challenge
357 // --> also for corr challenges
359 // Check that the players (if any indicated) are online
360 let chall = Object.Assign(
366 fen: this.newchallenge.fen || V.GenRandInitFen(),
367 variant: {id: this.newchallenge.vid, name: vname},
368 nbPlayers: this.newchallenge.nbPlayers,
370 {id: 0, name: this.newchallenge.to[0], sid: ""},
371 {id: 0, name: this.newchallenge.to[1], sid: ""},
372 {id: 0, name: this.newchallenge.to[2], sid: ""},
374 timeControl: this.newchallenge.timeControl,
376 for (let p of chall.to)
380 const pIdx = this.players.findIndex(pl => pl.name == p.name);
381 // NOTE: id (server DB) and sid (socket ID).
382 // Anonymous players just have a socket ID.
383 // NOTE: for correspondance play we don't require players to be online
384 // (==> we don't have IDs, and no sid)
385 if (liveGame && pIdx === -1)
386 return alert(p.name + " is not connected");
387 p.id = this.players[pIdx].id;
388 p.sid = this.players[pIdx].sid;
391 const finishAddChallenge = (cid) => {
392 chall.id = cid || "c" + getRandString();
393 this.challenges.push(chall);
394 // Send challenge to peers
397 code: "newchallenge",
401 const sendChallengeTo = (sid) => {
402 challSock.target = sid;
403 this.st.conn.send(JSON.stringify(challSock));
405 if (chall.to[0].id > 0)
407 // Challenge with targeted players
408 chall.to.forEach(p => {
410 sendChallengeTo(p.sid);
415 // Open challenge: send to all connected players (except us)
416 this.players.forEach(p => {
417 if (p.sid != this.st.user.sid) //only sid is always set
418 sendChallengeTo(p.sid);
421 document.getElementById("modalNewgame").checked = false;
423 if (this.newchallenge.liveGame)
425 // Live challenges have cid = 0
426 finishAddChallenge();
431 uid: req.body["from"],
432 vid: req.body["vid"],
433 fen: req.body["fen"],
434 timeControl: req.body["timeControl"],
435 nbPlayers: req.body["nbPlayers"],
436 to: req.body["to"], //array of IDs
438 // Correspondance game: send challenge to server
440 "/challenges/" + this.newchallenge.vid,
444 chall.id = response.cid;
445 finishAddChallenge();
450 possibleNbplayers: function(nbp) {
451 if (this.newchallenge.vid == 0)
453 const variants = this.st.variants;
454 const idxInVariants =
455 variants.findIndex(v => v.id == this.newchallenge.vid);
456 return NbPlayers[variants[idxInVariants].name].includes(nbp);