1 <!-- Main playing hall: online players + current challenges + button "new game" -->
5 input#modalNewgame.modal(type="checkbox")
6 div(role="dialog" aria-labelledby="titleFenedit")
8 label#closeNewgame.modal-close(for="modalNewgame")
10 label(for="selectVariant") {{ st.tr["Variant"] }}
11 select#selectVariant(v-model="newchallenge.vid")
12 option(v-for="v in st.variants" :value="v.id") {{ v.name }}
14 label(for="selectNbPlayers") {{ st.tr["Number of players"] }}
15 select#selectNbPlayers(v-model="newchallenge.nbPlayers")
16 option(v-show="possibleNbplayers(2)" value="2") 2
17 option(v-show="possibleNbplayers(3)" value="3") 3
18 option(v-show="possibleNbplayers(4)" value="4") 4
20 label(for="timeControl") {{ st.tr["Time control"] }}
21 input#timeControl(type="text" v-model="newchallenge.timeControl"
22 placeholder="3m+2s, 1h+30s, 7d+1d ...")
23 fieldset(v-if="st.user.id > 0")
24 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
26 input(type="text" v-model="newchallenge.to[0].name")
27 input(v-show="newchallenge.nbPlayers>=3" type="text"
28 v-model="newchallenge.to[1].name")
29 input(v-show="newchallenge.nbPlayers==4" type="text"
30 v-model="newchallenge.to[2].name")
31 fieldset(v-if="st.user.id > 0")
32 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
33 input#inputFen(type="text" v-model="newchallenge.fen")
34 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
36 .col-sm-12.col-md-5.col-md-offset-1.col-lg-4.col-lg-offset-2
38 button(@click="cpdisplay='challenges'") Challenges
39 button(@click="cpdisplay='players'") Players
40 ChallengeList(v-show="cpdisplay=='challenges'"
41 :challenges="challenges" @click-challenge="clickChallenge")
42 #players(v-show="cpdisplay=='players'")
44 div(v-for="p in uniquePlayers" @click="tryChallenge(p)")
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 { genRandString } 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:"askclients"}));
132 this.st.conn.onopen = socketOpenListener;
133 this.st.conn.onmessage = this.socketMessageListener;
134 const socketCloseListener = () => {
135 // connexion is reinitialized in store.js
136 this.st.conn.addEventListener('message', this.socketMessageListener);
137 this.st.conn.addEventListener('close', socketCloseListener);
139 this.st.conn.onclose = socketCloseListener;
142 socketMessageListener: function(msg) {
143 const data = JSON.parse(msg.data);
146 // 0.2] Receive clients list (just socket IDs)
148 data.sockIds.forEach(sid => {
149 this.players.push({sid:sid, id:0, name:""});
150 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
153 // TODO: also receive "askchallenges", "askgames"
155 // Request for identification
156 this.st.conn.send(JSON.stringify(
157 {code:"identity", user:this.st.user, target:data.from}));
160 if (data.user.id > 0) //otherwise "anonymous", nothing to retrieve
162 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
163 this.players[pIdx].id = data.user.id;
164 this.players[pIdx].name = data.user.name;
167 // * - receive "new game": if live, store locally + redirect to game
168 // * If corr: notify "new game has started", give link, but do not redirect
170 // TODO: new game just started: data contain all informations
171 // (id, players, time control, fenStart ...)
172 // + cid to remove challenge from list
174 // * - receive "playergame": a live game by some connected player (NO corr)
176 // TODO: receive live game summary (update, count moves)
177 // (just players names, time control, and ID + player ID)
179 // * - receive "playerchallenges": list of challenges (sent) by some online player (NO corr)
180 case "playerchallenges":
181 // TODO: receive challenge + challenge updates
183 case "newmove": //live or corr
184 // TODO: name conflict ? (game "newmove" event)
186 // * - receive new challenge: if targeted, replace our name with sender name
188 // receive live or corr challenge
189 this.challenges.push(data.chall);
191 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
192 case "acceptchallenge":
193 if (true) //TODO: if challenge is full
194 this.newGame(data.challenge, data.user); //user.id et user.name
196 case "withdrawchallenge":
197 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
198 let chall = this.challenges[cIdx]
199 ArrayFun.remove(chall.players, p => p.id == data.uid);
200 chall.players.push({id:0, name:""});
202 case "cancelchallenge":
203 ArrayFun.remove(this.challenges, c => c.id == data.cid);
205 // NOTE: finally only one connect / disconnect couple of events
206 // (because on server side we wouldn't know which to choose)
208 // * - receive "player connect": send all our current challenges (to him or global)
209 // * Also send all our games (live - max 1 - and corr) [in web worker ?]
210 // * + all our sent challenges.
211 this.players.push({name:"", id:0, sid:data.sid});
212 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
213 // TODO: si on est en train de jouer une partie, le notifier au nouveau connecté
214 // envoyer aussi nos défis
216 // * - receive "player disconnect": remove from players list
218 ArrayFun.remove(this.players, p => p.sid == data.sid);
219 // TODO: also remove all challenges sent by this player,
220 // and all live games where he plays and no other opponent is online
224 showGame: function(game) {
225 // NOTE: if we are an observer, the game will be found in main games list
226 // (sent by connected remote players)
227 // TODO: game path ? /vname/gameId seems better
228 this.$router.push("/" + game.id)
230 tryChallenge: function(player) {
232 return; //anonymous players cannot be challenged
233 this.newchallenge.players[0] = {
238 doClick("modalNewgame");
240 // * - accept challenge (corr or live) --> send info to all concerned players
241 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
242 // * - withdraw from challenge (if >= 3 players and previously accepted)
243 // * --> send info to all concerned players
244 // * - refuse challenge (or receive refusal): send to all challenge players (from + to)
245 // * except us ; graphics: modal again ? (inline ?)
246 // * - prepare and start new game (if challenge is full after acceptation)
247 // * --> include challenge ID (so that opponents can delete the challenge too)
248 // * Also send to all connected players (only from me)
249 clickChallenge: function(challenge) {
250 const index = this.challenges.findIndex(c => c.id == challenge.id);
251 const toIdx = challenge.to.findIndex(p => p.id == user.id);
252 const me = {name:user.name,id:user.id};
255 // It's a multiplayer challenge I accepted: withdraw
256 this.st.conn.send(JSON.stringify({code:"withdrawchallenge",
257 cid:challenge.id, user:me}));
258 this.challenges.to.splice(toIdx, 1);
260 else if (challenge.from.id == user.id) //it's my challenge: cancel it
262 this.st.conn.send(JSON.stringify({code:"cancelchallenge", cid:challenge.id}));
263 this.challenges.splice(index, 1);
265 else //accept a challenge
267 this.st.conn.send(JSON.stringify({code:"acceptchallenge",
268 cid:challenge.id, user:me}));
269 this.challenges[index].to.push(me);
271 // TODO: accepter un challenge peut lancer une partie, il
272 // faut alors supprimer challenge + creer partie + la retourner et l'ajouter ici
273 // si pas le mien et FEN speciale :: (charger code variante et)
274 // montrer diagramme + couleur (orienté)
276 // user: last person to accept the challenge (TODO: revoir ça)
277 // newGame: function(chall, user) {
278 // const fen = chall.fen || V.GenRandInitFen();
279 // const game = {}; //TODO: fen, players, time ...
280 // //setStorage(game); //TODO
281 // game.players.forEach(p => { //...even if game is by corr (could be played live, why not...)
283 // JSON.stringify({code:"newgame", oppid:p.id, game:game}));
285 // if (this.settings.sound >= 1)
286 // new Audio("/sounds/newgame.mp3").play().catch(err => {});
288 // Load a variant file (TODO: should probably be global)
289 loadVariant: async function(vid, variantArray) {
290 const idxInVariants = variantArray.findIndex(v => v.id == vid);
291 const vname = variantArray[idxInVariants].name;
292 const vModule = await import("@/variants/" + vname + ".js");
293 window.V = vModule.VariantRules;
296 // Send new challenge (corr or live, cf. time control), with button or click on player
297 newChallenge: async function() {
298 if (this.challenges.some(c => c.from.sid == this.st.user.sid))
300 document.getElementById("modalNewgame").checked = false;
301 return alert("You already have a pending challenge");
303 // TODO: put this "load variant" block elsewhere
304 const vname = this.loadVariant(this.newchallenge.vid, this.st.variants);
305 // checkChallenge side-effect = set FEN, and mainTime + increment in seconds
306 // TODO: should not be a side-effect but set here ; for received server challenges we do not have mainTime+increment
307 const error = checkChallenge(this.newchallenge);
310 // TODO: set FEN, set mainTime and increment ?!
311 else //generate a FEN
312 c.fen = V.GenRandInitFen();
313 // Less than 3 days ==> live game (TODO: heuristic... 40 moves also)
315 this.newchallenge.mainTime + 40 * this.newchallenge.increment < 3*24*60*60;
316 // Check that the players (if any indicated) are online
319 id: 0, //unknown yet (no ID for live challenges)
322 fen: this.newchallenge.fen,
323 variant: {id: this.newchallenge.vid, name: vname},
324 nbPlayers: this.newchallenge.nbPlayers,
326 {id: 0, name: this.newchallenge.to[0], sid: ""},
327 {id: 0, name: this.newchallenge.to[1], sid: ""},
328 {id: 0, name: this.newchallenge.to[2], sid: ""},
330 timeControl: this.newchallenge.timeControl,
331 mainTime: this.newchallenge.mainTime,
332 increment: this.newchallenge.increment,
334 for (let p of chall.to)
338 const pIdx = this.players.findIndex(pl => pl.name == p.name);
339 // NOTE: id (server DB) and sid (socket ID).
340 // Anonymous players just have a socket ID.
341 // NOTE: for correspondance play we don't require players to be online
342 // (==> we don't have IDs, and no sid)
343 if (liveGame && pIdx === -1)
344 return alert(p.name + " is not connected");
345 p.id = this.players[pIdx].id;
346 p.sid = this.players[pIdx].sid;
349 const finishAddChallenge = (cid) => {
350 chall.id = cid || "c" + genRandString();
351 this.challenges.push(chall);
352 // Send challenge to peers
355 code: "newchallenge",
359 const sendChallengeTo = (sid) => {
360 challSock.target = sid;
361 this.st.conn.send(JSON.stringify(challSock));
363 if (chall.to[0].id > 0)
365 // Challenge with targeted players
366 chall.to.forEach(p => {
368 sendChallengeTo(p.sid);
373 // Open challenge: send to all connected players (except us)
374 this.players.forEach(p => {
375 if (p.sid != this.st.user.sid) //only sid is always set
376 sendChallengeTo(p.sid);
379 document.getElementById("modalNewgame").checked = false;
383 // Live challenges have cid = 0
384 finishAddChallenge();
389 uid: req.body["from"],
390 vid: req.body["vid"],
391 fen: req.body["fen"],
392 timeControl: req.body["timeControl"],
393 nbPlayers: req.body["nbPlayers"],
394 to: req.body["to"], //array of IDs
396 // Correspondance game: send challenge to server
398 "/challenges/" + this.newchallenge.vid,
402 chall.id = response.cid;
403 finishAddChallenge();
408 possibleNbplayers: function(nbp) {
409 if (this.newchallenge.vid == 0)
411 const variants = this.st.variants;
412 const idxInVariants =
413 variants.findIndex(v => v.id == this.newchallenge.vid);
414 return NbPlayers[variants[idxInVariants].name].includes(nbp);