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 GameList from "@/components/GameList.vue";
83 import ChallengeList from "@/components/ChallengeList.vue";
84 import { GameStorage } from "@/utils/gameStorage";
85 import { extractTime } from "@/utils/timeControl";
95 cdisplay: "live", //or corr
96 pdisplay: "players", //or chat
100 players: [], //online players (rename into "people" ?)
105 to: ["", "", ""], //name(s) of challenged player(s)
106 timeControl: "", //"2m+2s" ...etc
111 uniquePlayers: function() {
112 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
113 let anonymous = {id:0, name:"@nonymous", count:0};
115 this.players.forEach(p => {
121 if (anonymous.count > 0)
122 playerList.push(anonymous);
126 created: function() {
127 // Always add myself to players' list
128 this.players.push(this.st.user);
129 if (this.st.user.id > 0)
131 // Ask server for current corr games (all but mines)
135 // {excluded: this.st.user.id},
137 // this.games = this.games.concat(response.games);
140 // Also ask for corr challenges (open + sent to me)
144 {uid: this.st.user.id},
146 console.log(response.challenges);
147 // TODO: post-treatment on challenges ?
148 this.challenges = this.challenges.concat(response.challenges);
152 // 0.1] Ask server for room composition:
153 const socketOpenListener = () => {
154 this.st.conn.send(JSON.stringify({code:"pollclients"}));
156 this.st.conn.onopen = socketOpenListener;
157 // TODO: is this required here?
158 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
159 this.st.conn.onmessage = this.socketMessageListener;
160 const oldOnclose = this.st.conn.onclose;
161 const socketCloseListener = () => {
162 oldOnclose(); //reinitialize connexion (in store.js)
163 this.st.conn.addEventListener('message', this.socketMessageListener);
164 this.st.conn.addEventListener('close', socketCloseListener);
166 this.st.conn.onclose = socketCloseListener;
170 filterChallenges: function(type) {
171 return this.challenges.filter(c => c.type == type);
173 filterGames: function(type) {
174 return this.games.filter(c => c.type == type);
176 classifyObject: function(o) { //challenge or game
177 // Heuristic: should work for most cases... (TODO)
178 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
180 possibleNbplayers: function(nbp) {
181 if (this.newchallenge.vid == 0)
183 const idxInVariants =
184 this.st.variants.findIndex(v => v.id == this.newchallenge.vid);
185 return NbPlayers[this.st.variants[idxInVariants].name].includes(nbp);
187 showGame: function(g) {
188 // NOTE: we are an observer, since only games I don't play are shown here
189 // ==> Moves sent by connected remote player(s) if live game
190 let url = "/" + g.id;
191 if (g.type == "live")
193 const sids = g.players.map(p => p.sid).join(",");
194 url += "?sids=" + sids;
196 this.$router.push(url);
198 getVname: function(vid) {
199 const vIdx = this.st.variants.findIndex(v => v.id == vid);
200 return this.st.variants[vIdx].name;
202 getSid: function(pname) {
203 const pIdx = this.players.findIndex(pl => pl.name == pname);
204 return (pIdx === -1 ? null : this.players[pIdx].sid);
206 getPname: function(sid) {
207 const pIdx = this.players.findIndex(pl => pl.sid == sid);
208 return (pIdx === -1 ? null : this.players[pIdx].name);
210 sendSomethingTo: function(to, code, obj, warnDisconnected) {
211 const doSend = (code, obj, sid) => {
212 this.st.conn.send(JSON.stringify(Object.assign(
221 to.forEach(pname => {
222 // Challenge with targeted players
223 const targetSid = this.getSid(pname);
226 if (!!warnDisconnected)
227 alert("Warning: " + pname + " is not connected");
230 doSend(code, obj, targetSid);
235 // Open challenge: send to all connected players (except us)
236 this.players.forEach(p => {
237 if (p.sid != this.st.user.sid) //only sid is always set
238 doSend(code, obj, p.sid);
243 socketMessageListener: function(msg) {
244 // Save and call current st.conn.onmessage if one was already defined
245 // --> also needed in future Game.vue (also in Chat.vue component)
246 this.oldOnmessage(msg);
247 const data = JSON.parse(msg.data);
250 // 0.2] Receive clients list (just socket IDs)
253 data.sockIds.forEach(sid => {
254 this.players.push({sid:sid, id:0, name:""});
255 // Ask identity, challenges and game(s)
256 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
257 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
258 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
264 // Request for identification: reply if I'm not anonymous
265 if (this.st.user.id > 0)
267 this.st.conn.send(JSON.stringify(
268 {code:"identity", user:this.st.user, target:data.from}));
274 // Send my current live challenge (if any)
275 const cIdx = this.challenges
276 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
279 const c = this.challenges[cIdx];
282 // Minimal challenge informations: (from not required)
287 timeControl: c.timeControl
289 this.st.conn.send(JSON.stringify({code:"challenge",
290 challenge:myChallenge, target:data.from}));
296 // Send my current live games (if any)
297 // TODO: from indexedDB, through GameStorage.
298 // if (!!localStorage["gid"])
302 // // Minimal game informations: (fen+clock not required)
303 // id: localStorage["gid"],
304 // players: JSON.parse(localStorage["players"]), //array sid+id+name
305 // vname: localStorage["vname"],
306 // timeControl: localStorage["timeControl"],
308 // this.st.conn.send(JSON.stringify({code:"game",
309 // game:myGame, target:data.from}));
315 const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
316 this.players[pIdx].id = data.user.id;
317 this.players[pIdx].name = data.user.name;
322 // Receive challenge from some player (+sid)
323 let newChall = data.chall;
324 newChall.type = this.classifyObject(data.chall);
325 const pIdx = this.players.findIndex(p => p.sid == data.from);
326 newChall.from = this.players[pIdx]; //may be anonymous
327 newChall.added = Date.now();
328 newChall.vname = this.getVname(newChall.vid);
329 this.challenges.push(newChall);
334 // Receive game from some player (+sid)
335 // NOTE: it may be correspondance (if newgame while we are connected)
336 // TODO: ambiguous naming "newGame" ==> rename function ?
337 let newGame = data.game;
338 newGame.type = this.classifyObject(data.game);
339 newGame.vname = newGame.vname;
340 this.games.push(newGame);
343 // * - receive "new game": if live, store locally + redirect to game
344 // * If corr: notify "new game has started", give link, but do not redirect
347 // Delete corresponding challenge:
348 ArrayFun.remove(this.challenges, c => c.id == data.cid);
349 // New game just started: data contain all informations
350 this.newGame(data.gameInfo);
353 // * - receive "accept/withdraw/cancel challenge": apply action to challenges list
354 // NOTE: challenge "socket" actions accept+withdraw only for live challenges
355 case "acceptchallenge":
357 // Someone accept an open (or targeted) challenge
358 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
359 let c = this.challenges[cIdx];
361 c.seats = [...Array(c.to.length)];
362 const pIdx = this.players.findIndex(p => p.sid == data.from);
363 // Put this player in the first empty seat we find:
365 for (; sIdx<c.seats.length; sIdx++)
369 c.seats[sIdx] = this.players[pIdx];
373 if (sIdx == c.seats.length - 1)
375 // All seats are taken: game can start
380 case "withdrawchallenge":
382 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
383 let seats = this.challenges[cIdx].seats;
384 const sIdx = seats.findIndex(s => s.sid == data.sid);
385 seats[sIdx] = undefined;
388 case "refusechallenge":
390 alert(this.getPname(data.from) + " refused your challenge");
391 ArrayFun.remove(this.challenges, c => c.id == data.cid);
394 case "deletechallenge":
396 ArrayFun.remove(this.challenges, c => c.id == data.cid);
401 this.players.push({name:"", id:0, sid:data.sid});
402 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
403 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
404 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
409 ArrayFun.remove(this.players, p => p.sid == data.sid);
410 // Also remove all challenges sent by this player:
411 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
412 // And all live games where he plays and no other opponent is online
413 ArrayFun.remove(this.games, g =>
414 g.type == "live" && (g.players.every(p => p.sid == data.sid
415 || !this.players.some(pl => pl.sid == p.sid))), "all");
420 // Challenge lifecycle:
421 tryChallenge: function(player) {
423 return; //anonymous players cannot be challenged
424 this.newchallenge.to[0] = player.name;
425 doClick("modalNewgame");
427 newChallenge: async function() {
428 const vname = this.getVname(this.newchallenge.vid);
429 const vModule = await import("@/variants/" + vname + ".js");
430 window.V = vModule.VariantRules;
431 const error = checkChallenge(this.newchallenge);
434 const ctype = this.classifyObject(this.newchallenge);
435 const cto = this.newchallenge.to.slice(0, this.newchallenge.nbPlayers - 1);
436 // NOTE: "from" information is not required here
439 fen: this.newchallenge.fen,
441 timeControl: this.newchallenge.timeControl,
442 vid: this.newchallenge.vid,
444 const finishAddChallenge = (cid,warnDisconnected) => {
445 chall.id = cid || "c" + getRandString();
446 // Send challenge to peers (if connected)
447 this.sendSomethingTo(cto, "challenge", {chall:chall}, !!warnDisconnected);
448 chall.added = Date.now();
451 chall.from = this.st.user;
452 this.challenges.push(chall);
453 document.getElementById("modalNewgame").checked = false;
455 const cIdx = this.challenges.findIndex(
456 c => c.from.sid == this.st.user.sid && c.type == ctype);
459 // Delete current challenge (will be replaced now)
460 this.sendSomethingTo(this.challenges[cIdx].to,
461 "deletechallenge", {cid:this.challenges[cIdx].id});
467 {id: this.challenges[cIdx].id}
470 this.challenges.splice(cIdx, 1);
474 // Live challenges have a random ID
475 finishAddChallenge(null, "warnDisconnected");
479 // Correspondance game: send challenge to server
484 response => { finishAddChallenge(response.cid); }
488 // * - accept challenge (corr or live) --> send info to challenge creator
489 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
490 // * - withdraw from challenge (if >= 3 players and previously accepted)
491 // * --> send info to challenge creator
492 // * - refuse challenge: send "refuse" to challenge sender, and "delete" to others
493 // * - prepare and start new game (if challenge is full after acceptation)
494 // * --> include challenge ID (so that opponents can delete the challenge too)
495 clickChallenge: function(c) {
497 console.log("click challenge");
502 this.st.conn.send(JSON.stringify({code: "withdrawchallenge",
503 cid: c.id, target: c.from.sid}));
504 if (c.type == "corr")
509 {action:"withdraw", id: this.challenges[cIdx].id}
514 else if (c.from.sid == this.st.user.sid
515 || (this.st.user.id > 0 && c.from.id == this.st.user.id))
517 // It's my challenge: cancel it
518 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
519 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
520 if (c.type == "corr")
525 {id: this.challenges[cIdx].id}
529 else //accept (or refuse) a challenge
534 // TODO: if special FEN, show diagram after loading variant
535 c.accepted = confirm("Accept challenge?");
537 this.st.conn.send(JSON.stringify({
538 code: (c.accepted ? "accept" : "refuse") + "challenge",
539 cid: c.id, target: c.from.sid}));
540 if (c.type == "corr" && c.accepted)
545 {action: "accept", id: this.challenges[cIdx].id}
550 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
551 if (c.type == "corr")
556 {id: this.challenges[cIdx].id}
562 // NOTE: for live games only (corr games are launched on server)
563 launchGame: async function(c) {
564 // Just assign colors and pass the message
565 const vname = this.getVname(c.vid);
566 const vModule = await import("@/variants/" + vname + ".js");
567 window.V = vModule.VariantRules;
568 let players = [c.from];
569 Array.prototype.push.apply(players, c.seats);
570 // These game informations will be sent to other players
573 gameId: getRandString(),
574 fen: c.fen || V.GenRandInitFen(),
575 // Players' names may be required if game start when a player is offline
576 // Shuffle players order (white then black then other colors).
577 players: shuffle(players.map(p => { return {name:p.name, sid:p.sid} })),
579 timeControl: c.timeControl,
581 c.seats.forEach(s => {
582 // NOTE: cid required to remove challenge
583 this.st.conn.send(JSON.stringify({code:"newgame",
584 gameInfo:gameInfo, cid:c.id, target:s.sid}));
586 // Delete corresponding challenge:
587 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
588 this.newGame(gameInfo); //also!
590 // NOTE: for live games only (corr games are launched on server)
591 newGame: function(gameInfo) {
592 // Extract times (in [milli]seconds), set clocks
593 const tc = extractTime(gameInfo.timeControl);
594 let initime = [...Array(gameInfo.players.length)];
595 initime[0] = Date.now();
598 // Game infos: constant
599 gameId: gameInfo.gameId,
600 vname: this.getVname(gameInfo.vid),
601 fenStart: gameInfo.fen,
602 players: gameInfo.players,
603 timeControl: gameInfo.timeControl,
604 increment: tc.increment,
605 mode: "live", //function for live games only
606 // Game state: will be updated
609 clocks: [...Array(gameInfo.players.length)].fill(tc.mainTime),
613 GameStorage.add(game);
614 if (this.st.settings.sound >= 1)
615 new Audio("/sounds/newgame.mp3").play().catch(err => {});
616 // TODO: redirect to game
628 // Remove duplicates if several players of one game send their game info (Hall)
629 // When click on it, assign a random rid among online players (max. 4).