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 { 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:"askclients"}));
132 this.st.conn.onopen = socketOpenListener;
133 this.oldOnmessage = this.st.conn.onmessage || Function.prototype; //TODO: required here?
134 this.st.conn.onmessage = this.socketMessageListener;
135 const oldOnclose = this.st.conn.onclose;
136 const socketCloseListener = () => {
137 oldOnclose(); //reinitialize connexion (in store.js)
138 this.st.conn.addEventListener('message', this.socketMessageListener);
139 this.st.conn.addEventListener('close', socketCloseListener);
141 this.st.conn.onclose = socketCloseListener;
144 socketMessageListener: function(msg) {
145 // Save and call current st.conn.onmessage if one was already defined
146 // --> also needed in future Game.vue (also in Chat.vue component)
147 // TODO: merge Game.vue and MoveList.vue (one logic entity, no ?)
148 this.oldOnmessage(msg);
149 const data = JSON.parse(msg.data);
152 // 0.2] Receive clients list (just socket IDs)
154 data.sockIds.forEach(sid => {
155 this.players.push({sid:sid, id:0, name:""});
156 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
159 // TODO: also receive "askchallenges", "askgames"
161 // Request for identification
162 this.st.conn.send(JSON.stringify(
163 {code:"identity", user:this.st.user, target:data.from}));
166 if (data.user.id > 0) //otherwise "anonymous", nothing to retrieve
168 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
169 this.players[pIdx].id = data.user.id;
170 this.players[pIdx].name = data.user.name;
173 // * - receive "new game": if live, store locally + redirect to game
174 // * If corr: notify "new game has started", give link, but do not redirect
176 // TODO: new game just started: data contain all informations
177 // (id, players, time control, fenStart ...)
178 // + cid to remove challenge from list
180 // * - receive "playergame": a live game by some connected player (NO corr)
182 // TODO: receive live game summary (update, count moves)
183 // (just players names, time control, and ID + player ID)
185 // * - receive "playerchallenges": list of challenges (sent) by some online player (NO corr)
186 case "playerchallenges":
187 // TODO: receive challenge + challenge updates
189 case "newmove": //live or corr
190 // TODO: name conflict ? (game "newmove" event)
192 // * - receive new challenge: if targeted, replace our name with sender name
194 // receive live or corr challenge
195 this.challenges.push(data.chall);
197 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
198 case "acceptchallenge":
199 if (true) //TODO: if challenge is full
200 this.newGame(data.challenge, data.user); //user.id et user.name
202 case "withdrawchallenge":
203 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
204 let chall = this.challenges[cIdx]
205 ArrayFun.remove(chall.players, p => p.id == data.uid);
206 chall.players.push({id:0, name:""});
208 case "cancelchallenge":
209 ArrayFun.remove(this.challenges, c => c.id == data.cid);
211 // NOTE: finally only one connect / disconnect couple of events
212 // (because on server side we wouldn't know which to choose)
214 // * - receive "player connect": send all our current challenges (to him or global)
215 // * Also send all our games (live - max 1 - and corr) [in web worker ?]
216 // * + all our sent challenges.
217 this.players.push({name:"", id:0, sid:data.sid});
218 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
219 // TODO: si on est en train de jouer une partie, le notifier au nouveau connecté
220 // envoyer aussi nos défis
222 // * - receive "player disconnect": remove from players list
224 ArrayFun.remove(this.players, p => p.sid == data.sid);
225 // TODO: also remove all challenges sent by this player,
226 // and all live games where he plays and no other opponent is online
230 showGame: function(game) {
231 // NOTE: if we are an observer, the game will be found in main games list
232 // (sent by connected remote players)
233 // TODO: game path ? /vname/gameId seems better
234 this.$router.push("/" + game.id)
236 tryChallenge: function(player) {
238 return; //anonymous players cannot be challenged
239 this.newchallenge.players[0] = {
244 doClick("modalNewgame");
246 // * - accept challenge (corr or live) --> send info to all concerned players
247 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
248 // * - withdraw from challenge (if >= 3 players and previously accepted)
249 // * --> send info to all concerned players
250 // * - refuse challenge (or receive refusal): send to all challenge players (from + to)
251 // * except us ; graphics: modal again ? (inline ?)
252 // * - prepare and start new game (if challenge is full after acceptation)
253 // * --> include challenge ID (so that opponents can delete the challenge too)
254 // * Also send to all connected players (only from me)
255 clickChallenge: function(challenge) {
256 const index = this.challenges.findIndex(c => c.id == challenge.id);
257 const toIdx = challenge.to.findIndex(p => p.id == user.id);
258 const me = {name:user.name,id:user.id};
261 // It's a multiplayer challenge I accepted: withdraw
262 this.st.conn.send(JSON.stringify({code:"withdrawchallenge",
263 cid:challenge.id, user:me}));
264 this.challenges.to.splice(toIdx, 1);
266 else if (challenge.from.id == user.id) //it's my challenge: cancel it
268 this.st.conn.send(JSON.stringify({code:"cancelchallenge", cid:challenge.id}));
269 this.challenges.splice(index, 1);
271 else //accept a challenge
273 this.st.conn.send(JSON.stringify({code:"acceptchallenge",
274 cid:challenge.id, user:me}));
275 this.challenges[index].to.push(me);
277 // TODO: accepter un challenge peut lancer une partie, il
278 // faut alors supprimer challenge + creer partie + la retourner et l'ajouter ici
279 // si pas le mien et FEN speciale :: (charger code variante et)
280 // montrer diagramme + couleur (orienté)
282 // user: last person to accept the challenge (TODO: revoir ça)
283 // newGame: function(chall, user) {
284 // const fen = chall.fen || V.GenRandInitFen();
285 // const game = {}; //TODO: fen, players, time ...
286 // //setStorage(game); //TODO
287 // game.players.forEach(p => { //...even if game is by corr (could be played live, why not...)
289 // JSON.stringify({code:"newgame", oppid:p.id, game:game}));
291 // if (this.settings.sound >= 1)
292 // new Audio("/sounds/newgame.mp3").play().catch(err => {});
294 // Load a variant file (TODO: should probably be global)
295 loadVariant: async function(vid, variantArray) {
296 const idxInVariants = variantArray.findIndex(v => v.id == vid);
297 const vname = variantArray[idxInVariants].name;
298 const vModule = await import("@/variants/" + vname + ".js");
299 window.V = vModule.VariantRules;
302 // Send new challenge (corr or live, cf. time control), with button or click on player
303 newChallenge: async function() {
304 if (this.challenges.some(c => c.from.sid == this.st.user.sid))
306 document.getElementById("modalNewgame").checked = false;
307 return alert("You already have a pending challenge");
309 // TODO: put this "load variant" block elsewhere
310 const vname = this.loadVariant(this.newchallenge.vid, this.st.variants);
311 // checkChallenge side-effect = set FEN, and mainTime + increment in seconds
312 // TODO: should not be a side-effect but set here ; for received server challenges we do not have mainTime+increment
313 const error = checkChallenge(this.newchallenge);
316 // TODO: set FEN, set mainTime and increment ?!
317 //else //generate a FEN
318 // c.fen = V.GenRandInitFen();
319 // Less than 3 days ==> live game (TODO: heuristic... 40 moves also)
321 this.newchallenge.mainTime + 40 * this.newchallenge.increment < 3*24*60*60;
322 // Check that the players (if any indicated) are online
325 id: 0, //unknown yet (no ID for live challenges)
328 fen: this.newchallenge.fen,
329 variant: {id: this.newchallenge.vid, name: vname},
330 nbPlayers: this.newchallenge.nbPlayers,
332 {id: 0, name: this.newchallenge.to[0], sid: ""},
333 {id: 0, name: this.newchallenge.to[1], sid: ""},
334 {id: 0, name: this.newchallenge.to[2], sid: ""},
336 timeControl: this.newchallenge.timeControl,
337 mainTime: this.newchallenge.mainTime,
338 increment: this.newchallenge.increment,
340 for (let p of chall.to)
344 const pIdx = this.players.findIndex(pl => pl.name == p.name);
345 // NOTE: id (server DB) and sid (socket ID).
346 // Anonymous players just have a socket ID.
347 // NOTE: for correspondance play we don't require players to be online
348 // (==> we don't have IDs, and no sid)
349 if (liveGame && pIdx === -1)
350 return alert(p.name + " is not connected");
351 p.id = this.players[pIdx].id;
352 p.sid = this.players[pIdx].sid;
355 const finishAddChallenge = (cid) => {
356 chall.id = cid || "c" + getRandString();
357 this.challenges.push(chall);
358 // Send challenge to peers
361 code: "newchallenge",
365 const sendChallengeTo = (sid) => {
366 challSock.target = sid;
367 this.st.conn.send(JSON.stringify(challSock));
369 if (chall.to[0].id > 0)
371 // Challenge with targeted players
372 chall.to.forEach(p => {
374 sendChallengeTo(p.sid);
379 // Open challenge: send to all connected players (except us)
380 this.players.forEach(p => {
381 if (p.sid != this.st.user.sid) //only sid is always set
382 sendChallengeTo(p.sid);
385 document.getElementById("modalNewgame").checked = false;
389 // Live challenges have cid = 0
390 finishAddChallenge();
395 uid: req.body["from"],
396 vid: req.body["vid"],
397 fen: req.body["fen"],
398 timeControl: req.body["timeControl"],
399 nbPlayers: req.body["nbPlayers"],
400 to: req.body["to"], //array of IDs
402 // Correspondance game: send challenge to server
404 "/challenges/" + this.newchallenge.vid,
408 chall.id = response.cid;
409 finishAddChallenge();
414 possibleNbplayers: function(nbp) {
415 if (this.newchallenge.vid == 0)
417 const variants = this.st.variants;
418 const idxInVariants =
419 variants.findIndex(v => v.id == this.newchallenge.vid);
420 return NbPlayers[variants[idxInVariants].name].includes(nbp);