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="timeControl") {{ st.tr["Time control"] }}
13 input#timeControl(type="text" v-model="newchallenge.timeControl"
14 placeholder="3m+2s, 1h+30s, 7d+1d ...")
15 fieldset(v-if="st.user.id > 0")
16 label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
17 input#selectPlayers(type="text" v-model="newchallenge.to")
18 fieldset(v-if="st.user.id > 0")
19 label(for="inputFen") {{ st.tr["FEN (optional)"] }}
20 input#inputFen(type="text" v-model="newchallenge.fen")
21 button(@click="newChallenge") {{ st.tr["Send challenge"] }}
23 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
24 button(onClick="doClick('modalNewgame')") New game
26 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
28 input#challengeSection(type="radio" checked aria-hidden="true" name="accordion")
29 label(for="challengeSection" aria-hidden="true") Challenges
32 button(@click="cdisplay='live'") Live Challenges
33 button(@click="cdisplay='corr'") Correspondance challenges
34 ChallengeList(v-show="cdisplay=='live'"
35 :challenges="filterChallenges('live')" @click-challenge="clickChallenge")
36 ChallengeList(v-show="cdisplay=='corr'"
37 :challenges="filterChallenges('corr')" @click-challenge="clickChallenge")
38 input#peopleSection(type="radio" aria-hidden="true" name="accordion")
39 label(for="peopleSection" aria-hidden="true") People
42 button(@click="pdisplay='players'") Players
43 button(@click="pdisplay='chat'") Chat
44 #players(v-show="pdisplay=='players'")
46 .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
47 :class="{anonymous: !!p.count}"
49 | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
50 #chat(v-show="pdisplay=='chat'")
52 input#gameSection(type="radio" aria-hidden="true" name="accordion")
53 label(for="gameSection" aria-hidden="true") Games
56 button(@click="gdisplay='live'") Live games
57 button(@click="gdisplay='corr'") Correspondance games
58 GameList(v-show="gdisplay=='live'" :games="filterGames('live')"
59 @show-game="showGame")
60 GameList(v-show="gdisplay=='corr'" :games="filterGames('corr')"
61 @show-game="showGame")
65 import { store } from "@/store";
66 import { checkChallenge } from "@/data/challengeCheck";
67 import { ArrayFun } from "@/utils/array";
68 import { ajax } from "@/utils/ajax";
69 import { getRandString, shuffle } from "@/utils/alea";
70 import GameList from "@/components/GameList.vue";
71 import ChallengeList from "@/components/ChallengeList.vue";
72 import { GameStorage } from "@/utils/gameStorage";
73 import { extractTime } from "@/utils/timeControl";
83 cdisplay: "live", //or corr
84 pdisplay: "players", //or chat
88 people: [], //(all) online players
92 to: "", //name of challenged player (if any)
93 timeControl: "", //"2m+2s" ...etc
98 uniquePlayers: function() {
99 // Show e.g. "@nonymous (5)", and do nothing on click on anonymous
100 let anonymous = {id:0, name:"@nonymous", count:0};
102 this.people.forEach(p => {
108 if (anonymous.count > 0)
109 playerList.push(anonymous);
113 created: function() {
114 // Always add myself to players' list
115 this.people.push(this.st.user);
116 // Retrieve live challenge (not older than 30 minute) if any:
117 const chall = JSON.parse(localStorage.getItem("challenge") || "false");
120 if ((Date.now() - chall.added)/1000 <= 30*60)
121 this.challenges.push(chall);
123 localStorage.removeItem("challenge");
125 if (this.st.user.id > 0)
127 // Ask server for current corr games (all but mines)
131 // {excluded: this.st.user.id},
133 // this.games = this.games.concat(response.games);
136 // Also ask for corr challenges (open + sent to me)
140 {uid: this.st.user.id},
142 console.log(response.challenges);
143 // TODO: post-treatment on challenges ?
144 this.challenges = this.challenges.concat(response.challenges);
148 // 0.1] Ask server for room composition:
149 const socketOpenListener = () => {
150 this.st.conn.send(JSON.stringify({code:"pollclients"}));
152 this.st.conn.onopen = socketOpenListener;
153 // TODO: is this required here?
154 this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
155 this.st.conn.onmessage = this.socketMessageListener;
156 const oldOnclose = this.st.conn.onclose;
157 const socketCloseListener = () => {
158 oldOnclose(); //reinitialize connexion (in store.js)
159 this.st.conn.addEventListener('message', this.socketMessageListener);
160 this.st.conn.addEventListener('close', socketCloseListener);
162 this.st.conn.onclose = socketCloseListener;
166 filterChallenges: function(type) {
167 return this.challenges.filter(c => c.type == type);
169 filterGames: function(type) {
170 return this.games.filter(c => c.type == type);
172 classifyObject: function(o) { //challenge or game
173 // Heuristic: should work for most cases... (TODO)
174 return (o.timeControl.indexOf('d') === -1 ? "live" : "corr");
176 showGame: function(g) {
177 // NOTE: we are an observer, since only games I don't play are shown here
178 // ==> Moves sent by connected remote player(s) if live game
180 // TODO: this doesn't work: choose a SID at random
181 // --> do we have players' names ?
183 let url = "/" + g.id;
184 if (g.type == "live")
186 const sids = g.players.map(p => p.sid).join(",");
187 url += "?sids=" + sids;
189 this.$router.push(url);
191 getVname: function(vid) {
192 const vIdx = this.st.variants.findIndex(v => v.id == vid);
193 return this.st.variants[vIdx].name;
195 getSid: function(pname) {
196 const pIdx = this.people.findIndex(pl => pl.name == pname);
197 return (pIdx === -1 ? null : this.people[pIdx].sid);
199 getPname: function(sid) {
200 const pIdx = this.people.findIndex(pl => pl.sid == sid);
201 return (pIdx === -1 ? null : this.people[pIdx].name);
203 sendSomethingTo: function(to, code, obj, warnDisconnected) {
204 const doSend = (code, obj, sid) => {
205 this.st.conn.send(JSON.stringify(Object.assign(
214 // Challenge with targeted players
215 const targetSid = this.getSid(to);
218 if (!!warnDisconnected)
219 alert("Warning: " + pname + " is not connected");
222 doSend(code, obj, targetSid);
226 // Open challenge: send to all connected players (except us)
227 this.people.forEach(p => {
228 if (p.sid != this.st.user.sid) //only sid is always set
229 doSend(code, obj, p.sid);
234 socketMessageListener: function(msg) {
235 // Save and call current st.conn.onmessage if one was already defined
236 // --> also needed in future Game.vue (also in Chat.vue component)
237 this.oldOnmessage(msg);
238 const data = JSON.parse(msg.data);
241 // 0.2] Receive clients list (just socket IDs)
244 data.sockIds.forEach(sid => {
245 this.people.push({sid:sid, id:0, name:""});
246 // Ask identity, challenges and game(s)
247 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
248 this.st.conn.send(JSON.stringify({code:"askchallenge", target:sid}));
249 this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
255 // Request for identification: reply if I'm not anonymous
256 if (this.st.user.id > 0)
258 this.st.conn.send(JSON.stringify(
259 {code:"identity", user:this.st.user, target:data.from}));
265 // Send my current live challenge (if any)
266 const cIdx = this.challenges
267 .findIndex(c => c.from.sid == this.st.user.sid && c.type == "live");
270 const c = this.challenges[cIdx];
273 // Minimal challenge informations: (from not required)
278 timeControl: c.timeControl
280 this.st.conn.send(JSON.stringify({code:"challenge",
281 chall:myChallenge, target:data.from}));
287 // Send my current live game (if any)
288 GameStorage.getCurrent((game) => {
293 // Minimal game informations:
295 players: game.players.map(p => p.name),
297 timeControl: game.timeControl,
299 this.st.conn.send(JSON.stringify({code:"game",
300 game:myGame, target:data.from}));
307 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
308 this.people[pIdx].id = data.user.id;
309 this.people[pIdx].name = data.user.name;
314 // Receive challenge from some player (+sid)
315 let newChall = data.chall;
316 newChall.type = this.classifyObject(data.chall);
317 const pIdx = this.people.findIndex(p => p.sid == data.from);
318 newChall.from = this.people[pIdx]; //may be anonymous
319 newChall.added = Date.now(); //TODO: this is reception timestamp, not creation
320 newChall.vname = this.getVname(newChall.vid); //TODO: just send vname?
321 this.challenges.push(newChall);
326 // Receive game from some player (+sid)
327 // NOTE: it may be correspondance (if newgame while we are connected)
328 let newGame = data.game;
329 newGame.type = this.classifyObject(data.game);
330 newGame.rid = data.from;
332 this.games.push(newGame);
335 // * - receive "new game": if live, store locally + redirect to game
336 // * If corr: notify "new game has started", give link, but do not redirect
339 // Delete corresponding challenge:
340 ArrayFun.remove(this.challenges, c => c.id == data.cid);
341 // New game just started: data contain all informations
342 this.startNewGame(data.gameInfo);
345 // * - receive "accept/cancel challenge": apply action to challenges list
346 // NOTE: challenge "socket" actions accept+withdraw only for live challenges
347 case "acceptchallenge":
349 // Someone accept an open (or targeted) challenge
350 const cIdx = this.challenges.findIndex(c => c.id == data.cid);
351 let c = this.challenges[cIdx];
352 const pIdx = this.people.findIndex(p => p.sid == data.from);
353 c.seat = this.people[pIdx];
357 case "refusechallenge":
359 alert(this.getPname(data.from) + " refused your challenge");
360 ArrayFun.remove(this.challenges, c => c.id == data.cid);
363 case "deletechallenge":
365 // NOTE: the challenge may be already removed
366 ArrayFun.remove(this.challenges, c => c.id == data.cid);
371 this.people.push({name:"", id:0, sid:data.sid});
372 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
373 this.st.conn.send(JSON.stringify({code:"askchallenge", target:data.sid}));
374 this.st.conn.send(JSON.stringify({code:"askgame", target:data.sid}));
379 ArrayFun.remove(this.people, p => p.sid == data.sid);
380 // Also remove all challenges sent by this player:
381 ArrayFun.remove(this.challenges, c => c.from.sid == data.sid);
382 // And all live games where he plays and no other opponent is online
383 ArrayFun.remove(this.games, g =>
384 g.type == "live" && (g.players.every(p => p.sid == data.sid
385 || !this.people.some(pl => pl.sid == p.sid))), "all");
390 // Challenge lifecycle:
391 tryChallenge: function(player) {
393 return; //anonymous players cannot be challenged
394 this.newchallenge.to[0] = player.name;
395 doClick("modalNewgame");
397 newChallenge: async function() {
398 const vname = this.getVname(this.newchallenge.vid);
399 const vModule = await import("@/variants/" + vname + ".js");
400 window.V = vModule.VariantRules;
401 const error = checkChallenge(this.newchallenge);
404 const ctype = this.classifyObject(this.newchallenge);
405 // NOTE: "from" information is not required here
408 fen: this.newchallenge.fen,
409 to: this.newchallenge.to,
410 timeControl: this.newchallenge.timeControl,
411 vid: this.newchallenge.vid,
413 const finishAddChallenge = (cid,warnDisconnected) => {
414 chall.id = cid || "c" + getRandString();
415 // Send challenge to peers (if connected)
416 this.sendSomethingTo(chall.to, "challenge", {chall:chall}, !!warnDisconnected);
417 chall.added = Date.now();
420 chall.from = this.st.user;
421 this.challenges.push(chall);
422 localStorage.setItem("challenge", JSON.stringify(chall));
423 document.getElementById("modalNewgame").checked = false;
425 const cIdx = this.challenges.findIndex(
426 c => c.from.sid == this.st.user.sid && c.type == ctype);
429 // Delete current challenge (will be replaced now)
430 this.sendSomethingTo(this.challenges[cIdx].to,
431 "deletechallenge", {cid:this.challenges[cIdx].id});
437 {id: this.challenges[cIdx].id}
440 this.challenges.splice(cIdx, 1);
444 // Live challenges have a random ID
445 finishAddChallenge(null, "warnDisconnected");
449 // Correspondance game: send challenge to server
454 response => { finishAddChallenge(response.cid); }
458 // * - accept challenge (corr or live) --> send info to challenge creator
459 // * - cancel challenge (click on sent challenge) --> send info to all concerned players
460 // * --> send info to challenge creator
461 // * - refuse challenge: send "refuse" to challenge sender, and "delete" to others
462 // * - prepare and start new game (if challenge is full after acceptation)
463 // * --> include challenge ID (so that opponents can delete the challenge too)
464 clickChallenge: function(c) {
466 console.log("click challenge");
469 if (c.from.sid == this.st.user.sid
470 || (this.st.user.id > 0 && c.from.id == this.st.user.id))
472 // It's my challenge: cancel it
473 this.sendSomethingTo(c.to, "deletechallenge", {cid:c.id});
474 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
475 if (c.type == "corr")
480 {id: this.challenges[cIdx].id}
484 else //accept (or refuse) a challenge
489 // TODO: if special FEN, show diagram after loading variant
490 c.accepted = confirm("Accept challenge?");
492 this.st.conn.send(JSON.stringify({
493 code: (c.accepted ? "accept" : "refuse") + "challenge",
494 cid: c.id, target: c.from.sid}));
497 if (c.type == "corr")
502 {id: this.challenges[cIdx].id}
508 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
509 if (!c.to) //TODO: send to everyone except me and opponent ?
510 this.sendSomethingTo("", "deletechallenge", {cid: this.challenges[cIdx].id});
511 if (c.type == "corr")
516 {id: this.challenges[cIdx].id}
522 // NOTE: for live games only (corr games are launched on server)
523 launchGame: async function(c) {
524 // Just assign colors and pass the message
525 const vname = this.getVname(c.vid);
526 const vModule = await import("@/variants/" + vname + ".js");
527 window.V = vModule.VariantRules;
528 let players = [c.from, c.seat];
529 // These game informations will be sent to other players
532 gameId: getRandString(),
533 fen: c.fen || V.GenRandInitFen(),
534 // Players' names may be required if game start when a player is offline
535 // Shuffle players order (white then black then other colors).
536 players: shuffle(players.map(p => { return {name:p.name, sid:p.sid} })),
538 timeControl: c.timeControl,
540 // NOTE: cid required to remove challenge
541 this.st.conn.send(JSON.stringify({code:"newgame",
542 gameInfo:gameInfo, cid:c.id, target:c.seat.sid}));
543 // Delete corresponding challenge:
544 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
545 this.startNewGame(gameInfo); //also!
547 // NOTE: for live games only (corr games are launched on server)
548 startNewGame: function(gameInfo) {
549 // Extract times (in [milli]seconds), set clocks
550 const tc = extractTime(gameInfo.timeControl);
551 let initime = [...Array(gameInfo.players.length)];
552 initime[0] = Date.now();
555 // Game infos: constant
556 gameId: gameInfo.gameId,
557 vname: this.getVname(gameInfo.vid),
558 fenStart: gameInfo.fen,
559 players: gameInfo.players,
560 timeControl: gameInfo.timeControl,
561 increment: tc.increment,
562 mode: "live", //function for live games only
563 // Game state: will be updated
566 clocks: [...Array(gameInfo.players.length)].fill(tc.mainTime),
570 GameStorage.add(game);
571 if (this.st.settings.sound >= 1)
572 new Audio("/sounds/newgame.mp3").play().catch(err => {});
573 // TODO: redirect to game
585 // Remove duplicates if several players of one game send their game info (Hall)
586 // When click on it, assign a random rid among online players (max. 4).