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-5.col-md-offset-1.col-lg-4.col-lg-offset-2
36 button(@click="cpdisplay='challenges'") Challenges
37 button(@click="cpdisplay='players'") Players
38 ChallengeList(v-show="cpdisplay=='challenges'"
39 :challenges="challenges" @click-challenge="clickChallenge")
40 #players(v-show="cpdisplay=='players'")
42 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
43 :class="{anonymous: !!p.count}"
45 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
47 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
48 button(onClick="doClick('modalNewgame')") New game
50 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
52 button(@click="gdisplay='live'") Live games
53 button(@click="gdisplay='corr'") Correspondance games
54 GameList(v-show="gdisplay=='live'" :games="liveGames"
55 @show-game="showGame")
56 GameList(v-show="gdisplay=='corr'" :games="corrGames"
57 @show-game="showGame")
61 import { store } from "@/store";
62 import { NbPlayers } from "@/data/nbPlayers";
63 import { checkChallenge } from "@/data/challengeCheck";
64 import { ArrayFun } from "@/utils/array";
65 import { ajax } from "@/utils/ajax";
66 import { getRandString } from "@/utils/alea";
67 import GameList from "@/components/GameList.vue";
68 import ChallengeList from "@/components/ChallengeList.vue";
78 cpdisplay: "challenges",
83 players: [], //online players
88 to: ["", "", ""], //name of challenged players
89 timeControl: "", //"2m+2s" ...etc
94 uniquePlayers: function() {
95 // Show e.g. "5 @nonymous", and do nothing on click on anonymous
96 let anonymous = {id:0, name:"@nonymous", count:0};
98 this.players.forEach(p => {
104 if (anonymous.count > 0)
105 playerList.push(anonymous);
109 created: function() {
110 // Always add myself to players' list
111 this.players.push(this.st.user);
112 // Ask server for current corr games (all but mines)
120 // // Also ask for corr challenges (all)
128 // 0.1] Ask server for for room composition:
129 const socketOpenListener = () => {
130 this.st.conn.send(JSON.stringify({code:"pollclients"}));
132 this.st.conn.onopen = socketOpenListener;
133 // TODO: is this required here?
134 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
135 this.st.conn.onmessage = this.socketMessageListener;
136 const oldOnclose = this.st.conn.onclose;
137 const socketCloseListener = () => {
138 oldOnclose(); //reinitialize connexion (in store.js)
139 this.st.conn.addEventListener('message', this.socketMessageListener);
140 this.st.conn.addEventListener('close', socketCloseListener);
142 this.st.conn.onclose = socketCloseListener;
145 socketMessageListener: function(msg) {
146 // Save and call current st.conn.onmessage if one was already defined
147 // --> also needed in future Game.vue (also in Chat.vue component)
148 // TODO: merge Game.vue and MoveList.vue (one logic entity, no ?)
149 this.oldOnmessage(msg);
150 const data = JSON.parse(msg.data);
153 // 0.2] Receive clients list (just socket IDs)
155 data.sockIds.forEach(sid => {
156 this.players.push({sid:sid, id:0, name:""});
157 // Ask identity, challenges and game(s)
158 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
159 this.st.conn.send(JSON.stringify({code:"askchallenges", target:sid}));
160 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
164 // Request for identification
165 this.st.conn.send(JSON.stringify(
166 {code:"identity", user:this.st.user, target:data.from}));
168 case "askchallenges":
169 // Send my current challenges
170 const myChallenges = this.challenges
171 .filter(c => c.from.sid == this.st.user.sid)
173 // Minimal challenge informations: (from not required)
177 timeControl: c.timeControl
179 if (myChallenges.length > 0)
181 this.st.conn.send(JSON.stringify({code:"challenges",
182 challenges:myChallenges, target:data.from})
186 // TODO: Send my current live game (if any)
189 if (data.user.id > 0) //otherwise "anonymous", nothing to retrieve
191 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
192 this.players[pIdx].id = data.user.id;
193 this.players[pIdx].name = data.user.name;
197 // Receive challenges from some player
200 // Receive live game from some player
202 // * - receive "new game": if live, store locally + redirect to game
203 // * If corr: notify "new game has started", give link, but do not redirect
205 // TODO: new game just started: data contain all informations
206 // (id, players, time control, fenStart ...)
207 // + cid to remove challenge from list
209 // * - receive "playergame": a live game by some connected player (NO corr)
211 // TODO: receive live game summary (update, count moves)
212 // (just players names, time control, and ID + player ID)
214 // * - receive "playerchallenges": list of challenges (sent) by some online player (NO corr)
215 case "playerchallenges":
216 // TODO: receive challenge + challenge updates
218 case "newmove": //live or corr
219 // TODO: name conflict ? (game "newmove" event)
221 // * - receive new challenge: if targeted, replace our name with sender name
223 // receive live or corr challenge
224 this.challenges.push(data.chall);
226 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
227 case "acceptchallenge":
228 if (true) //TODO: if challenge is full
229 this.newGame(data.challenge, data.user); //user.id et user.name
231 case "withdrawchallenge":
232 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
233 let chall = this.challenges[cIdx]
234 ArrayFun.remove(chall.players, p => p.id == data.uid);
235 chall.players.push({id:0, name:""});
237 case "cancelchallenge":
238 ArrayFun.remove(this.challenges, c => c.id == data.cid);
240 // NOTE: finally only one connect / disconnect couple of events
241 // (because on server side we wouldn't know which to choose)
243 // * - receive "player connect": send all our current challenges (to him or global)
244 // * Also send all our games (live - max 1 - and corr) [in web worker ?]
245 // * + all our sent challenges.
246 this.players.push({name:"", id:0, sid:data.sid});
247 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
248 // TODO: si on est en train de jouer une partie, le notifier au nouveau connecté
249 // envoyer aussi nos défis
251 // * - receive "player disconnect": remove from players list
253 ArrayFun.remove(this.players, p => p.sid == data.sid);
254 // TODO: also remove all challenges sent by this player,
255 // and all live games where he plays and no other opponent is online
259 showGame: function(game) {
260 // NOTE: if we are an observer, the game will be found in main games list
261 // (sent by connected remote players)
262 // TODO: game path ? /vname/gameId seems better
263 this.$router.push("/" + game.id)
265 tryChallenge: function(player) {
267 return; //anonymous players cannot be challenged
268 this.newchallenge.to[0] = player.name;
269 doClick("modalNewgame");
271 // * - accept challenge (corr or live) --> send info to all concerned players
272 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
273 // * - withdraw from challenge (if >= 3 players and previously accepted)
274 // * --> send info to all concerned players
275 // * - refuse challenge (or receive refusal): send to all challenge players (from + to)
276 // * except us ; graphics: modal again ? (inline ?)
277 // * - prepare and start new game (if challenge is full after acceptation)
278 // * --> include challenge ID (so that opponents can delete the challenge too)
279 // * Also send to all connected players (only from me)
280 clickChallenge: function(challenge) {
281 // TODO: also correspondance case (send to server)
282 const index = this.challenges.findIndex(c => c.id == challenge.id);
283 const toIdx = challenge.to.findIndex(name => name == this.st.user.name);
286 // It's a multiplayer challenge I accepted: withdraw
287 this.st.conn.send(JSON.stringify({code:"withdrawchallenge",
288 cid:challenge.id, user:this.st.user.sid}));
289 this.challenges.to.splice(toIdx, 1);
291 else if (challenge.from.id == user.id) //it's my challenge: cancel it
293 this.st.conn.send(JSON.stringify({code:"cancelchallenge", cid:challenge.id}));
294 this.challenges.splice(index, 1);
296 else //accept a challenge
298 this.st.conn.send(JSON.stringify({code:"acceptchallenge",
299 cid:challenge.id, user:me}));
300 this.challenges[index].to.push(me);
302 // TODO: accepter un challenge peut lancer une partie, il
303 // faut alors supprimer challenge + creer partie + la retourner et l'ajouter ici
304 // si pas le mien et FEN speciale :: (charger code variante et)
305 // montrer diagramme + couleur (orienté)
307 // user: last person to accept the challenge (TODO: revoir ça)
308 // newGame: function(chall, user) {
309 // const fen = chall.fen || V.GenRandInitFen();
310 // const game = {}; //TODO: fen, players, time ...
311 // //setStorage(game); //TODO
312 // game.players.forEach(p => { //...even if game is by corr (could be played live, why not...)
314 // JSON.stringify({code:"newgame", oppid:p.id, game:game}));
316 // if (this.settings.sound >= 1)
317 // new Audio("/sounds/newgame.mp3").play().catch(err => {});
319 // Load a variant file (TODO: should probably be global)
320 loadVariant: async function(vid, variantArray) {
321 const idxInVariants = variantArray.findIndex(v => v.id == vid);
322 const vname = variantArray[idxInVariants].name;
323 const vModule = await import("@/variants/" + vname + ".js");
324 window.V = vModule.VariantRules;
327 // Send new challenge (corr or live, cf. time control), with button or click on player
328 newChallenge: async function() {
329 if (this.challenges.some(c => c.from.sid == this.st.user.sid))
331 document.getElementById("modalNewgame").checked = false;
332 return alert("You already have a pending challenge");
334 // TODO: put this "load variant" block elsewhere
335 const vname = this.loadVariant(this.newchallenge.vid, this.st.variants);
336 // checkChallenge side-effect = set FEN, and mainTime + increment in seconds
337 // TODO: should not be a side-effect but set here ; for received server challenges we do not have mainTime+increment
338 const error = checkChallenge(this.newchallenge);
341 // TODO: set FEN, set mainTime and increment ?!
342 //else //generate a FEN
343 // c.fen = V.GenRandInitFen();
344 // Less than 3 days ==> live game (TODO: heuristic... 40 moves also)
346 this.newchallenge.mainTime + 40 * this.newchallenge.increment < 3*24*60*60;
347 // Check that the players (if any indicated) are online
348 let chall = Object.Assign(
354 fen: this.newchallenge.fen,
355 variant: {id: this.newchallenge.vid, name: vname},
356 nbPlayers: this.newchallenge.nbPlayers,
358 {id: 0, name: this.newchallenge.to[0], sid: ""},
359 {id: 0, name: this.newchallenge.to[1], sid: ""},
360 {id: 0, name: this.newchallenge.to[2], sid: ""},
362 timeControl: this.newchallenge.timeControl,
364 for (let p of chall.to)
368 const pIdx = this.players.findIndex(pl => pl.name == p.name);
369 // NOTE: id (server DB) and sid (socket ID).
370 // Anonymous players just have a socket ID.
371 // NOTE: for correspondance play we don't require players to be online
372 // (==> we don't have IDs, and no sid)
373 if (liveGame && pIdx === -1)
374 return alert(p.name + " is not connected");
375 p.id = this.players[pIdx].id;
376 p.sid = this.players[pIdx].sid;
379 const finishAddChallenge = (cid) => {
380 chall.id = cid || "c" + getRandString();
381 this.challenges.push(chall);
382 // Send challenge to peers
385 code: "newchallenge",
389 const sendChallengeTo = (sid) => {
390 challSock.target = sid;
391 this.st.conn.send(JSON.stringify(challSock));
393 if (chall.to[0].id > 0)
395 // Challenge with targeted players
396 chall.to.forEach(p => {
398 sendChallengeTo(p.sid);
403 // Open challenge: send to all connected players (except us)
404 this.players.forEach(p => {
405 if (p.sid != this.st.user.sid) //only sid is always set
406 sendChallengeTo(p.sid);
409 document.getElementById("modalNewgame").checked = false;
413 // Live challenges have cid = 0
414 finishAddChallenge();
419 uid: req.body["from"],
420 vid: req.body["vid"],
421 fen: req.body["fen"],
422 timeControl: req.body["timeControl"],
423 nbPlayers: req.body["nbPlayers"],
424 to: req.body["to"], //array of IDs
426 // Correspondance game: send challenge to server
428 "/challenges/" + this.newchallenge.vid,
432 chall.id = response.cid;
433 finishAddChallenge();
438 possibleNbplayers: function(nbp) {
439 if (this.newchallenge.vid == 0)
441 const variants = this.st.variants;
442 const idxInVariants =
443 variants.findIndex(v => v.id == this.newchallenge.vid);
444 return NbPlayers[variants[idxInVariants].name].includes(nbp);