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, shuffle } from "@/utils/alea";
82 import { extractTime } from "@/utils/timeControl";
83 import GameList from "@/components/GameList.vue";
84 import ChallengeList from "@/components/ChallengeList.vue";
94 cdisplay: "live", //or corr
95 pdisplay: "players", //or chat
99 players: [], //online players (rename into "people" ?)
104 to: ["", "", ""], //name(s) of challenged player(s)
105 timeControl: "", //"2m+2s" ...etc
110 uniquePlayers: function() {
111 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
112 let anonymous = {id:0, name:"@nonymous", count:0};
114 this.players.forEach(p => {
120 if (anonymous.count > 0)
121 playerList.push(anonymous);
125 created: function() {
126 // Always add myself to players' list
127 this.players.push(this.st.user);
128 if (this.st.user.id > 0)
130 // Ask server for current corr games (all but mines)
134 // {excluded: this.st.user.id},
136 // this.games = this.games.concat(response.games);
139 // Also ask for corr challenges (open + sent to me)
143 {uid: this.st.user.id},
145 console.log(response.challenges);
146 // TODO: post-treatment on challenges ?
147 this.challenges = this.challenges.concat(response.challenges);
151 // 0.1] Ask server for room composition:
152 const socketOpenListener = () => {
153 this.st.conn.send(JSON.stringify({code:"pollclients"}));
155 this.st.conn.onopen = socketOpenListener;
156 // TODO: is this required here?
157 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
158 this.st.conn.onmessage = this.socketMessageListener;
159 const oldOnclose = this.st.conn.onclose;
160 const socketCloseListener = () => {
161 oldOnclose(); //reinitialize connexion (in store.js)
162 this.st.conn.addEventListener('message', this.socketMessageListener);
163 this.st.conn.addEventListener('close', socketCloseListener);
165 this.st.conn.onclose = socketCloseListener;
169 filterChallenges: function(type) {
170 return this.challenges.filter(c => c.type == type);
172 filterGames: function(type) {
173 return this.games.filter(c => c.type == type);
175 classifyObject: function(o) { //challenge or game
176 // Heuristic: should work for most cases... (TODO)
177 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
179 possibleNbplayers: function(nbp) {
180 if (this.newchallenge.vid == 0)
182 const idxInVariants =
183 this.st.variants.findIndex(v => v.id == this.newchallenge.vid);
184 return NbPlayers[this.st.variants[idxInVariants].name].includes(nbp);
186 showGame: function(g) {
187 // NOTE: we are an observer, since only games I don't play are shown here
188 // ==> Moves sent by connected remote player(s) if live game
189 let url = "/" + g.id;
190 if (g.type == "live")
192 const sids = g.players.map(p => p.sid).join(",");
193 url += "?sids=" + sids;
195 this.$router.push(url);
197 getVname: function(vid) {
198 const vIdx = this.st.variants.findIndex(v => v.id == vid);
199 return this.st.variants[vIdx].name;
201 getSid: function(pname) {
202 const pIdx = this.players.findIndex(pl => pl.name == pname);
203 return (pIdx === -1 ? null : this.players[pIdx].sid);
205 getPname: function(sid) {
206 const pIdx = this.players.findIndex(pl => pl.sid == sid);
207 return (pIdx === -1 ? null : this.players[pIdx].name);
209 sendSomethingTo: function(to, code, obj, warnDisconnected) {
210 const doSend = (code, obj, sid) => {
211 this.st.conn.send(JSON.stringify(Object.assign(
220 to.forEach(pname => {
221 // Challenge with targeted players
222 const targetSid = this.getSid(pname);
225 if (!!warnDisconnected)
226 alert("Warning: " + pname + " is not connected");
229 doSend(code, obj, targetSid);
234 // Open challenge: send to all connected players (except us)
235 this.players.forEach(p => {
236 if (p.sid != this.st.user.sid) //only sid is always set
237 doSend(code, obj, p.sid);
242 socketMessageListener: function(msg) {
243 // Save and call current st.conn.onmessage if one was already defined
244 // --> also needed in future Game.vue (also in Chat.vue component)
245 this.oldOnmessage(msg);
246 const data = JSON.parse(msg.data);
249 // 0.2] Receive clients list (just socket IDs)
252 data.sockIds.forEach(sid => {
253 this.players.push({sid:sid, id:0, name:""});
254 // Ask identity, challenges and game(s)
255 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
256 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
257 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
263 // Request for identification: reply if I'm not anonymous
264 if (this.st.user.id > 0)
266 this.st.conn.send(JSON.stringify(
267 {code:"identity", user:this.st.user, target:data.from}));
273 // Send my current live challenge (if any)
274 const cIdx = this.challenges
275 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
278 const c = this.challenges[cIdx];
281 // Minimal challenge informations: (from not required)
286 timeControl: c.timeControl
288 this.st.conn.send(JSON.stringify({code:"challenge",
289 challenge:myChallenge, target:data.from}));
295 // Send my current live game (if any)
296 if (!!localStorage["gid"])
300 // Minimal game informations: (fen+clock not required)
301 id: localStorage["gid"],
302 players: JSON.parse(localStorage["players"]), //array sid+id+name
303 vname: localStorage["vname"],
304 timeControl: localStorage["timeControl"],
306 this.st.conn.send(JSON.stringify({code:"game",
307 game:myGame, target:data.from}));
313 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
314 this.players[pIdx].id = data.user.id;
315 this.players[pIdx].name = data.user.name;
320 // Receive challenge from some player (+sid)
321 let newChall = data.chall;
322 newChall.type = this.classifyObject(data.chall);
323 const pIdx = this.players.findIndex(p => p.sid == data.from);
324 newChall.from = this.players[pIdx]; //may be anonymous
325 newChall.added = Date.now();
326 newChall.vname = this.getVname(newChall.vid);
327 this.challenges.push(newChall);
332 // Receive game from some player (+sid)
333 // NOTE: it may be correspondance (if newgame while we are connected)
334 let newGame = data.game;
335 newGame.type = this.classifyObject(data.game);
336 newGame.vname = newGame.vname;
337 this.games.push(newGame);
340 // * - receive "new game": if live, store locally + redirect to game
341 // * If corr: notify "new game has started", give link, but do not redirect
344 // Delete corresponding challenge:
345 ArrayFun.remove(this.challenges, c => c.id == data.cid);
346 // New game just started: data contain all informations
347 this.newGame(data.gameInfo);
350 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
351 // NOTE: challenge "socket" actions accept+withdraw only for live challenges
352 case "acceptchallenge":
354 // Someone accept an open (or targeted) challenge
355 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
356 let c = this.challenges[cIdx];
358 c.seats = [...Array(c.to.length)];
359 const pIdx = this.players.findIndex(p => p.sid == data.from);
360 // Put this player in the first empty seat we find:
362 for (; sIdx<c.seats.length; sIdx++)
366 c.seats[sIdx] = this.players[pIdx];
370 if (sIdx == c.seats.length - 1)
372 // All seats are taken: game can start
377 case "withdrawchallenge":
379 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
380 let seats = this.challenges[cIdx].seats;
381 const sIdx = seats.findIndex(s => s.sid == data.sid);
382 seats[sIdx] = undefined;
385 case "refusechallenge":
387 alert(this.getPname(data.from) + " refused your challenge");
388 ArrayFun.remove(this.challenges, c => c.id == data.cid);
391 case "deletechallenge":
393 ArrayFun.remove(this.challenges, c => c.id == data.cid);
398 this.players.push({name:"", id:0, sid:data.sid});
399 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
400 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
401 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
406 ArrayFun.remove(this.players, p => p.sid == data.sid);
407 // Also remove all challenges sent by this player:
408 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
409 // And all live games where he plays and no other opponent is online
410 ArrayFun.remove(this.games, g =>
411 g.type == "live" && (g.players.every(p => p.sid == data.sid
412 || !this.players.some(pl => pl.sid == p.sid))), "all");
417 // Challenge lifecycle:
418 tryChallenge: function(player) {
420 return; //anonymous players cannot be challenged
421 this.newchallenge.to[0] = player.name;
422 doClick("modalNewgame");
424 newChallenge: async function() {
425 const vname = this.getVname(this.newchallenge.vid);
426 const vModule = await import("@/variants/" + vname + ".js");
427 window.V = vModule.VariantRules;
428 const error = checkChallenge(this.newchallenge);
431 const ctype = this.classifyObject(this.newchallenge);
432 const cto = this.newchallenge.to.slice(0, this.newchallenge.nbPlayers - 1);
433 // NOTE: "from" information is not required here
436 fen: this.newchallenge.fen,
438 timeControl: this.newchallenge.timeControl,
439 vid: this.newchallenge.vid,
441 const finishAddChallenge = (cid,warnDisconnected) => {
442 chall.id = cid || "c" + getRandString();
443 // Send challenge to peers (if connected)
444 this.sendSomethingTo(cto, "challenge", {chall:chall}, !!warnDisconnected);
445 chall.added = Date.now();
448 chall.from = this.st.user;
449 this.challenges.push(chall);
450 document.getElementById("modalNewgame").checked = false;
452 const cIdx = this.challenges.findIndex(
453 c => c.from.sid == this.st.user.sid && c.type == ctype);
456 // Delete current challenge (will be replaced now)
457 this.sendSomethingTo(this.challenges[cIdx].to,
458 "deletechallenge", {cid:this.challenges[cIdx].id});
464 {id: this.challenges[cIdx].id}
467 this.challenges.splice(cIdx, 1);
471 // Live challenges have a random ID
472 finishAddChallenge(null, "warnDisconnected");
476 // Correspondance game: send challenge to server
481 response => { finishAddChallenge(response.cid); }
485 // * - accept challenge (corr or live) --> send info to challenge creator
486 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
487 // * - withdraw from challenge (if >= 3 players and previously accepted)
488 // * --> send info to challenge creator
489 // * - refuse challenge: send "refuse" to challenge sender, and "delete" to others
490 // * - prepare and start new game (if challenge is full after acceptation)
491 // * --> include challenge ID (so that opponents can delete the challenge too)
492 clickChallenge: function(c) {
494 console.log("click challenge");
499 this.st.conn.send(JSON.stringify({code: "withdrawchallenge",
500 cid: c.id, target: c.from.sid}));
501 if (c.type == "corr")
506 {action:"withdraw", id: this.challenges[cIdx].id}
511 else if (c.from.sid == this.st.user.sid
512 || (this.st.user.id > 0 && c.from.id == this.st.user.id))
514 // It's my challenge: cancel it
515 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
516 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
517 if (c.type == "corr")
522 {id: this.challenges[cIdx].id}
526 else //accept (or refuse) a challenge
531 // TODO: if special FEN, show diagram after loading variant
532 c.accepted = confirm("Accept challenge?");
534 this.st.conn.send(JSON.stringify({
535 code: (c.accepted ? "accept" : "refuse") + "challenge",
536 cid: c.id, target: c.from.sid}));
537 if (c.type == "corr" && c.accepted)
542 {action: "accept", id: this.challenges[cIdx].id}
547 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
548 if (c.type == "corr")
553 {id: this.challenges[cIdx].id}
559 // NOTE: for live games only (corr games are launched on server)
560 launchGame: async function(c) {
561 // Just assign colors and pass the message
562 const vname = this.getVname(c.vid);
563 const vModule = await import("@/variants/" + vname + ".js");
564 window.V = vModule.VariantRules;
565 let players = [c.from];
566 Array.prototype.push.apply(players, c.seats);
569 fen: c.fen || V.GenRandInitFen(),
570 // Shuffle players order (white then black then other colors).
571 // Players' names may be required if game start when a player is offline
572 players: shuffle(players).map(p => { return {name:p.name, sid:p.sid} }),
574 timeControl: c.timeControl,
576 c.seats.forEach(s => {
577 // NOTE: cid required to remove challenge
578 this.st.conn.send(JSON.stringify({code:"newgame",
579 gameInfo:gameInfo, cid:c.id, target:s.sid}));
581 // Delete corresponding challenge:
582 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
583 this.newGame(gameInfo); //also!
585 // NOTE: for live games only (corr games are launched on server)
586 newGame: function(gameInfo) {
587 GameStorage.init(); //TODO here
589 localStorage["gid"] = getRandString();
590 // Extract times (in [milli]seconds), set clocks, store in localStorage
591 const tc = extractTime(gameInfo.timeControl);
592 localStorage["timeControl"] = gameInfo.timeControl;
593 localStorage["clocks"] = JSON.stringify(
594 [...Array(gameInfo.players.length)].fill(tc.mainTime));
595 localStorage["increment"] = tc.increment;
596 localStorage["started"] = JSON.stringify(
597 [...Array(gameInfo.players.length)].fill(false));
598 localStorage["vname"] = this.getVname(gameInfo.vid);
599 localStorage["fenInit"] = gameInfo.fen;
600 localStorage["players"] = JSON.stringify(gameInfo.players);
601 if (this.st.settings.sound >= 1)
602 new Audio("/sounds/newgame.mp3").play().catch(err => {});
603 // TODO: redirect to game