Fix games ordering in MyGames, fix en-passant mistake in Rifle variant
[vchess.git] / client / src / views / Hall.vue
1 <template lang="pug">
2 main
3 input#modalInfo.modal(type="checkbox")
4 div#infoDiv(
5 role="dialog"
6 data-checkbox="modalInfo"
7 )
8 .card.text-center
9 label.modal-close(for="modalInfo")
10 p(v-html="infoMessage")
11 input#modalAccept.modal(type="checkbox")
12 div#acceptDiv(role="dialog")
13 .card
14 p.text-center
15 span.variantName {{ curChallToAccept.vname }}
16 span {{ curChallToAccept.cadence }}
17 span {{ st.tr["with"] + " " + curChallToAccept.from.name }}
18 .diagram(
19 v-if="!!curChallToAccept.fen"
20 v-html="tchallDiag"
21 )
22 .button-group#buttonsTchall(:style="tchallButtonsMargin()")
23 button.acceptBtn(@click="decisionChallenge(true)")
24 span {{ st.tr["Accept challenge?"] }}
25 button.refuseBtn(@click="decisionChallenge(false)")
26 span {{ st.tr["Refuse"] }}
27 input#modalNewgame.modal(
28 type="checkbox"
29 @change="cadenceFocusIfOpened($event)"
30 )
31 div#newgameDiv(
32 role="dialog"
33 data-checkbox="modalNewgame"
34 )
35 .card
36 label#closeNewgame.modal-close(for="modalNewgame")
37 div(@keyup.enter="newChallenge()")
38 fieldset
39 label(for="selectVariant") {{ st.tr["Variant"] }} *
40 select#selectVariant(
41 @change="loadNewchallVariant(trySetNewchallDiag)"
42 v-model="newchallenge.vid"
43 )
44 option(
45 v-for="v in st.variants"
46 :value="v.id"
47 :selected="newchallenge.vid==v.id"
48 )
49 | {{ v.name }}
50 fieldset
51 label(for="cadence") {{ st.tr["Cadence"] }} *
52 div#predefinedCadences
53 button(type="button") 15+5
54 button(type="button") 45+30
55 button(type="button") 3d
56 button(type="button") 7d
57 input#cadence(
58 type="text"
59 v-model="newchallenge.cadence"
60 placeholder="5+0, 1h+30s, 5d ..."
61 )
62 fieldset
63 label(for="selectRandomLevel") {{ st.tr["Randomness"] }} *
64 select#selectRandomLevel(v-model="newchallenge.randomness")
65 option(value="0") {{ st.tr["Deterministic"] }}
66 option(value="1") {{ st.tr["Symmetric random"] }}
67 option(value="2") {{ st.tr["Asymmetric random"] }}
68 fieldset(v-if="st.user.id > 0")
69 label(for="selectPlayers") {{ st.tr["Play with?"] }}
70 input#selectPlayers(
71 type="text"
72 v-model="newchallenge.to"
73 )
74 fieldset(v-if="st.user.id > 0 && newchallenge.to.length > 0")
75 input#inputFen(
76 placeholder="FEN"
77 @input="trySetNewchallDiag()"
78 type="text"
79 v-model="newchallenge.fen"
80 )
81 .diagram(v-html="newchallenge.diag")
82 button(@click="newChallenge()") {{ st.tr["Send challenge"] }}
83 input#modalPeople.modal(
84 type="checkbox"
85 @click="resetSocialColor()"
86 )
87 div#peopleWrap(
88 role="dialog"
89 data-checkbox="modalPeople"
90 )
91 .card
92 label.modal-close(for="modalPeople")
93 #people
94 #players
95 p(
96 v-for="sid in Object.keys(people)"
97 v-if="!!people[sid].name"
98 )
99 span {{ people[sid].name }}
100 button.player-action(
101 v-if="isGamer(sid)"
102 @click="watchGame(sid)"
103 )
104 | {{ st.tr["Observe"] }}
105 button.player-action(
106 v-else-if="isFocusedOnHall(sid)"
107 @click="challenge(sid)"
108 )
109 | {{ st.tr["Challenge"] }}
110 p.anonymous @nonymous ({{ anonymousCount }})
111 #chat
112 Chat(
113 :newChat="newChat"
114 @mychat="processChat"
115 :pastChats="[]"
116 )
117 .clearer
118 .row
119 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
120 .button-group
121 button#peopleBtn(onClick="window.doClick('modalPeople')")
122 | {{ st.tr["Who's there?"] }}
123 button(@click="showNewchallengeForm()")
124 | {{ st.tr["New game"] }}
125 .row
126 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
127 div#div2
128 .button-group
129 button.tabbtn#btnClive(@click="setDisplay('c','live',$event)")
130 | {{ st.tr["Live challenges"] }}
131 button.tabbtn#btnCcorr(@click="setDisplay('c','corr',$event)")
132 | {{ st.tr["Correspondance challenges"] }}
133 ChallengeList(
134 v-show="cdisplay=='live'"
135 :challenges="filterChallenges('live')"
136 @click-challenge="clickChallenge"
137 )
138 ChallengeList(
139 v-show="cdisplay=='corr'"
140 :challenges="filterChallenges('corr')"
141 @click-challenge="clickChallenge"
142 )
143 div#div3
144 .button-group
145 button.tabbtn#btnGlive(@click="setDisplay('g','live',$event)")
146 | {{ st.tr["Live games"] }}
147 button.tabbtn#btnGcorr(@click="setDisplay('g','corr',$event)")
148 | {{ st.tr["Correspondance games"] }}
149 GameList(
150 v-show="gdisplay=='live'"
151 :games="filterGames('live')"
152 :showBoth="true"
153 @show-game="showGame"
154 )
155 GameList(
156 v-show="gdisplay=='corr'"
157 :games="filterGames('corr')"
158 :showBoth="true"
159 @show-game="showGame"
160 )
161 </template>
162
163 <script>
164 import { store } from "@/store";
165 import { checkChallenge } from "@/data/challengeCheck";
166 import { ArrayFun } from "@/utils/array";
167 import { ajax } from "@/utils/ajax";
168 import params from "@/parameters";
169 import { getRandString, shuffle } from "@/utils/alea";
170 import { getDiagram } from "@/utils/printDiagram";
171 import Chat from "@/components/Chat.vue";
172 import GameList from "@/components/GameList.vue";
173 import ChallengeList from "@/components/ChallengeList.vue";
174 import { GameStorage } from "@/utils/gameStorage";
175 import { processModalClick } from "@/utils/modalClick";
176 export default {
177 name: "my-hall",
178 components: {
179 Chat,
180 GameList,
181 ChallengeList
182 },
183 data: function() {
184 return {
185 st: store.state,
186 cdisplay: "live", //or corr
187 gdisplay: "live",
188 games: [],
189 challenges: [],
190 people: {},
191 infoMessage: "",
192 newchallenge: {
193 fen: "",
194 vid: parseInt(localStorage.getItem("vid")) || 0,
195 to: "", //name of challenged player (if any)
196 cadence: localStorage.getItem("cadence") || "",
197 randomness: parseInt(localStorage.getItem("randomness")) || 2,
198 // VariantRules object, stored to not interfere with
199 // diagrams of targetted challenges:
200 V: null,
201 vname: "",
202 diag: "" //visualizing FEN
203 },
204 tchallDiag: "",
205 curChallToAccept: {from: {}},
206 newChat: "",
207 conn: null,
208 connexionString: "",
209 // Related to (killing of) self multi-connects:
210 newConnect: {},
211 killed: {}
212 };
213 },
214 watch: {
215 // st.variants changes only once, at loading from [] to [...]
216 "st.variants": function() {
217 // Set potential challenges and games variant names:
218 this.challenges.concat(this.games).forEach(o => {
219 if (!o.vname) o.vname = this.getVname(o.vid);
220 });
221 if (!this.newchallenge.V && this.newchallenge.vid > 0)
222 this.loadNewchallVariant();
223 }
224 },
225 computed: {
226 anonymousCount: function() {
227 let count = 0;
228 Object.values(this.people).forEach(p => {
229 // Do not cound people who did not send their identity yet:
230 count += (!p.name && p.id === 0) ? 1 : 0;
231 });
232 return count;
233 }
234 },
235 created: function() {
236 if (this.st.variants.length > 0 && this.newchallenge.vid > 0)
237 this.loadNewchallVariant();
238 const my = this.st.user;
239 this.$set(
240 this.people,
241 my.sid,
242 {
243 id: my.id,
244 name: my.name,
245 pages: [{ path: "/", focus: true }]
246 }
247 );
248 // Ask server for current corr games (all but mines)
249 ajax(
250 "/games",
251 "GET",
252 {
253 data: { uid: this.st.user.id, excluded: true },
254 success: (response) => {
255 this.games = this.games.concat(
256 response.games.map(g => {
257 const type = this.classifyObject(g);
258 const vname = this.getVname(g.vid);
259 return Object.assign(
260 {},
261 g,
262 {
263 type: type,
264 vname: vname,
265 priority: g.score == "*" ? 1 : 0 //for display
266 }
267 );
268 })
269 );
270 }
271 }
272 );
273 // Also ask for corr challenges (open + sent by/to me)
274 ajax(
275 "/challenges",
276 "GET",
277 {
278 data: { uid: this.st.user.id },
279 success: (response) => {
280 // Gather all senders names, and then retrieve full identity:
281 // (TODO [perf]: some might be online...)
282 let names = {};
283 response.challenges.forEach(c => {
284 if (c.uid != this.st.user.id) names[c.uid] = "";
285 else if (!!c.target && c.target != this.st.user.id)
286 names[c.target] = "";
287 });
288 const addChallenges = () => {
289 names[this.st.user.id] = this.st.user.name; //in case of
290 this.challenges = this.challenges.concat(
291 response.challenges.map(c => {
292 const from = { name: names[c.uid], id: c.uid }; //or just name
293 const type = this.classifyObject(c);
294 const vname = this.getVname(c.vid);
295 return Object.assign(
296 {},
297 {
298 type: type,
299 vname: vname,
300 from: from,
301 to: c.target ? names[c.target] : ""
302 },
303 c
304 );
305 })
306 );
307 };
308 if (Object.keys(names).length > 0) {
309 ajax(
310 "/users",
311 "GET",
312 {
313 data: { ids: Object.keys(names).join(",") },
314 success: (response2) => {
315 response2.users.forEach(u => {
316 names[u.id] = u.name;
317 });
318 addChallenges();
319 }
320 }
321 );
322 } else addChallenges();
323 }
324 }
325 );
326 const connectAndPoll = () => {
327 this.send("connect");
328 this.send("pollclientsandgamers");
329 };
330 // Initialize connection
331 this.connexionString =
332 params.socketUrl +
333 "/?sid=" +
334 this.st.user.sid +
335 "&id=" +
336 this.st.user.id +
337 "&tmpId=" +
338 getRandString() +
339 "&page=" +
340 // Hall: path is "/" (could be hard-coded as well)
341 encodeURIComponent(this.$route.path);
342 this.conn = new WebSocket(this.connexionString);
343 this.conn.onopen = connectAndPoll;
344 this.conn.onmessage = this.socketMessageListener;
345 this.conn.onclose = this.socketCloseListener;
346 },
347 mounted: function() {
348 document.addEventListener('visibilitychange', this.visibilityChange);
349 ["peopleWrap", "infoDiv", "newgameDiv"].forEach(eltName => {
350 let elt = document.getElementById(eltName);
351 elt.addEventListener("click", processModalClick);
352 });
353 document.querySelectorAll("#predefinedCadences > button").forEach(b => {
354 b.addEventListener("click", () => {
355 this.newchallenge.cadence = b.innerHTML;
356 });
357 });
358 const dispCorr = this.$route.query["disp"];
359 const showCtype =
360 dispCorr || localStorage.getItem("type-challenges") || "live";
361 const showGtype =
362 dispCorr || localStorage.getItem("type-games") || "live";
363 this.setDisplay("c", showCtype);
364 this.setDisplay("g", showGtype);
365 },
366 beforeDestroy: function() {
367 document.removeEventListener('visibilitychange', this.visibilityChange);
368 this.send("disconnect");
369 },
370 methods: {
371 visibilityChange: function() {
372 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
373 this.send(
374 document.visibilityState == "visible"
375 ? "getfocus"
376 : "losefocus"
377 );
378 },
379 partialResetNewchallenge: function() {
380 // Reset potential target and custom FEN:
381 this.newchallenge.to = "";
382 this.newchallenge.fen = "";
383 this.newchallenge.diag = "";
384 },
385 showNewchallengeForm: function() {
386 this.partialResetNewchallenge();
387 window.doClick("modalNewgame");
388 },
389 tchallButtonsMargin: function() {
390 if (!!this.curChallToAccept.fen) return { "margin-top": "10px" };
391 return {};
392 },
393 cadenceFocusIfOpened: function() {
394 if (event.target.checked)
395 document.getElementById("cadence").focus();
396 },
397 send: function(code, obj) {
398 if (!!this.conn) {
399 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
400 }
401 },
402 getVname: function(vid) {
403 const variant = this.st.variants.find(v => v.id == vid);
404 // this.st.variants might be uninitialized (variant == null)
405 return variant ? variant.name : "";
406 },
407 filterChallenges: function(type) {
408 return this.challenges.filter(c => c.type == type);
409 },
410 filterGames: function(type) {
411 return this.games.filter(g => g.type == type);
412 },
413 classifyObject: function(o) {
414 //challenge or game
415 return o.cadence.indexOf("d") === -1 ? "live" : "corr";
416 },
417 setDisplay: function(letter, type, e) {
418 this[letter + "display"] = type;
419 localStorage.setItem(
420 "type-" + (letter == "c" ? "challenges" : "games"),
421 type
422 );
423 let elt = e
424 ? e.target
425 : document.getElementById("btn" + letter.toUpperCase() + type);
426 elt.classList.add("active");
427 elt.classList.remove("somethingnew"); //in case of
428 if (!!elt.previousElementSibling)
429 elt.previousElementSibling.classList.remove("active");
430 else elt.nextElementSibling.classList.remove("active");
431 },
432 isGamer: function(sid) {
433 return this.people[sid].pages
434 .some(p => p.focus && p.path.indexOf("/game/") >= 0);
435 },
436 isFocusedOnHall: function(sid) {
437 return (
438 // This is meant to challenge people, thus the next 2 conditions:
439 this.st.user.id > 0 &&
440 sid != this.st.user.sid &&
441 this.people[sid].pages.some(p => p.path == "/" && p.focus)
442 );
443 },
444 challenge: function(sid) {
445 this.partialResetNewchallenge();
446 // Available, in Hall
447 this.newchallenge.to = this.people[sid].name;
448 document.getElementById("modalPeople").checked = false;
449 window.doClick("modalNewgame");
450 },
451 watchGame: function(sid) {
452 // In some game, maybe playing maybe not: show a random one
453 let gids = [];
454 this.people[sid].pages.forEach(p => {
455 if (p.focus) {
456 const matchGid = p.path.match(/[a-zA-Z0-9]+$/);
457 if (!!matchGid) gids.push(matchGid[0]);
458 }
459 });
460 const gid = gids[Math.floor(Math.random() * gids.length)];
461 const game = this.games.find(g => g.id == gid);
462 if (!!game) this.showGame(game);
463 else this.$router.push("/game/" + gid); //game vs. me
464 },
465 showGame: function(g) {
466 // NOTE: we are an observer, since only games I don't play are shown here
467 // ==> Moves sent by connected remote player(s) if live game
468 let url = "/game/" + g.id;
469 if (g.type == "live")
470 url += "?rid=" + g.rids[Math.floor(Math.random() * g.rids.length)];
471 this.$router.push(url);
472 },
473 resetSocialColor: function() {
474 // TODO: this is called twice, once on opening an once on closing
475 document.getElementById("peopleBtn").classList.remove("somethingnew");
476 },
477 processChat: function(chat) {
478 this.send("newchat", { data: chat });
479 },
480 getOppsid: function(c) {
481 let oppsid = c.from.sid; //may not be defined if corr + offline opp
482 if (!oppsid) {
483 oppsid = Object.keys(this.people).find(
484 sid => this.people[sid].id == c.from.id
485 );
486 }
487 return oppsid;
488 },
489 // Messaging center:
490 socketMessageListener: function(msg) {
491 if (!this.conn) return;
492 const data = JSON.parse(msg.data);
493 switch (data.code) {
494 case "pollclientsandgamers": {
495 // Since people can be both in Hall and Game,
496 // need to track "askIdentity" requests:
497 let identityAsked = {};
498 data.sockIds.forEach(s => {
499 const page = s.page || "/";
500 if (s.sid != this.st.user.sid && !identityAsked[s.sid]) {
501 this.send("askidentity", { target: s.sid, page: page });
502 identityAsked[s.sid] = true;
503 }
504 if (!this.people[s.sid]) {
505 // Do not set name or id: identity unknown yet
506 this.people[s.sid] = { pages: [{path: page, focus: true}] };
507 }
508 else if (!(this.people[s.sid].pages.find(p => p.path == page)))
509 this.people[s.sid].pages.push({ path: page, focus: true });
510 if (!s.page)
511 // Peer is in Hall
512 this.send("askchallenge", { target: s.sid });
513 // Peer is in Game
514 else this.send("askgame", { target: s.sid, page: page });
515 });
516 break;
517 }
518 case "connect":
519 case "gconnect": {
520 const page = data.page || "/";
521 // Only ask game / challenge if first connexion:
522 if (!this.people[data.from]) {
523 this.people[data.from] = { pages: [{ path: page, focus: true }] };
524 if (data.code == "connect")
525 this.send("askchallenge", { target: data.from });
526 else this.send("askgame", { target: data.from, page: page });
527 } else {
528 // Append page if not already in list
529 if (!(this.people[data.from].pages.find(p => p.path == page)))
530 this.people[data.from].pages.push({ path: page, focus: true });
531 }
532 if (!this.people[data.from].name && this.people[data.from].id !== 0) {
533 // Identity not known yet
534 this.newConnect[data.from] = true; //for self multi-connects tests
535 this.send("askidentity", { target: data.from, page: page });
536 }
537 break;
538 }
539 case "disconnect":
540 case "gdisconnect": {
541 // If the user reloads the page twice very quickly (experienced with Firefox),
542 // the first reload won't have time to connect but will trigger a "close" event anyway.
543 // ==> Next check is required.
544 if (!this.people[data.from]) return;
545 // Disconnect means no more tmpIds:
546 if (data.code == "disconnect") {
547 // Remove the live challenge sent by this player:
548 ArrayFun.remove(
549 this.challenges,
550 c => c.type == "live" && c.from.sid == data.from
551 );
552 } else {
553 // Remove the matching live game if now unreachable
554 const gid = data.page.match(/[a-zA-Z0-9]+$/)[0];
555 const gidx = this.games.findIndex(g => g.id == gid);
556 if (gidx >= 0) {
557 const game = this.games[gidx];
558 if (
559 game.type == "live" &&
560 game.rids.length == 1 &&
561 game.rids[0] == data.from
562 ) {
563 this.games.splice(gidx, 1);
564 }
565 }
566 }
567 const page = data.page || "/";
568 ArrayFun.remove(this.people[data.from].pages, p => p.path == page);
569 if (this.people[data.from].pages.length == 0)
570 this.$delete(this.people, data.from);
571 break;
572 }
573 case "getfocus":
574 // If user reload a page, focus may arrive earlier than connect
575 if (!!this.people[data.from]) {
576 this.people[data.from].pages
577 .find(p => p.path == data.page).focus = true;
578 this.$forceUpdate(); //TODO: shouldn't be required
579 }
580 break;
581 case "losefocus":
582 if (!!this.people[data.from]) {
583 this.people[data.from].pages
584 .find(p => p.path == data.page).focus = false;
585 this.$forceUpdate(); //TODO: shouldn't be required
586 }
587 break;
588 case "killed":
589 // I logged in elsewhere:
590 this.conn = null;
591 alert(this.st.tr["New connexion detected: tab now offline"]);
592 break;
593 case "askidentity": {
594 // Request for identification (TODO: anonymous shouldn't need to reply)
595 const me = {
596 // Decompose to avoid revealing email
597 name: this.st.user.name,
598 sid: this.st.user.sid,
599 id: this.st.user.id
600 };
601 this.send("identity", { data: me, target: data.from });
602 break;
603 }
604 case "identity": {
605 const user = data.data;
606 let player = this.people[user.sid];
607 // player.pages is already set
608 player.id = user.id;
609 player.name = user.name;
610 // TODO: this.$set(people, ...) fails. So forceUpdate.
611 // But this shouldn't be like that!
612 this.$forceUpdate();
613 // If I multi-connect, kill current connexion if no mark (I'm older)
614 if (this.newConnect[user.sid]) {
615 if (
616 user.id > 0 &&
617 user.id == this.st.user.id &&
618 user.sid != this.st.user.sid &&
619 !this.killed[this.st.user.sid]
620 ) {
621 this.send("killme", { sid: this.st.user.sid });
622 this.killed[this.st.user.sid] = true;
623 }
624 delete this.newConnect[user.sid];
625 }
626 break;
627 }
628 case "askchallenge": {
629 // Send my current live challenge (if any)
630 const cIdx = this.challenges.findIndex(
631 c => c.from.sid == this.st.user.sid && c.type == "live"
632 );
633 if (cIdx >= 0) {
634 const c = this.challenges[cIdx];
635 // NOTE: in principle, should only send targeted challenge to the target.
636 // But we may not know yet the identity of the target (just name),
637 // so cannot decide if data.from is the target or not.
638 const myChallenge = {
639 id: c.id,
640 from: this.st.user.sid,
641 to: c.to,
642 randomness: c.randomness,
643 fen: c.fen,
644 vid: c.vid,
645 cadence: c.cadence,
646 added: c.added
647 };
648 this.send("challenge", { data: myChallenge, target: data.from });
649 }
650 break;
651 }
652 case "challenge": //after "askchallenge"
653 case "newchallenge": {
654 // NOTE about next condition: see "askchallenge" case.
655 const chall = data.data;
656 if (
657 !chall.to ||
658 (this.people[chall.from].id > 0 &&
659 (chall.from == this.st.user.sid || chall.to == this.st.user.name))
660 ) {
661 let newChall = Object.assign({}, chall);
662 newChall.type = this.classifyObject(chall);
663 newChall.randomness = chall.randomness;
664 newChall.added = Date.now();
665 let fromValues = Object.assign({}, this.people[chall.from]);
666 delete fromValues["pages"]; //irrelevant in this context
667 newChall.from = Object.assign({ sid: chall.from }, fromValues);
668 newChall.vname = this.getVname(newChall.vid);
669 this.challenges.push(newChall);
670 if (
671 (newChall.type == "live" && this.cdisplay == "corr") ||
672 (newChall.type == "corr" && this.cdisplay == "live")
673 ) {
674 document
675 .getElementById("btnC" + newChall.type)
676 .classList.add("somethingnew");
677 }
678 }
679 break;
680 }
681 case "refusechallenge": {
682 const cid = data.data;
683 ArrayFun.remove(this.challenges, c => c.id == cid);
684 alert(this.st.tr["Challenge declined"]);
685 break;
686 }
687 case "deletechallenge": {
688 // NOTE: the challenge may be already removed
689 const cid = data.data;
690 ArrayFun.remove(this.challenges, c => c.id == cid);
691 break;
692 }
693 case "game": //individual request
694 case "newgame": {
695 const game = data.data;
696 // Ignore games where I play (will go in MyGames page)
697 if (game.players.every(p =>
698 p.sid != this.st.user.sid || p.uid != this.st.user.id))
699 {
700 let locGame = this.games.find(g => g.id == game.id);
701 if (!locGame) {
702 let newGame = game;
703 newGame.type = this.classifyObject(game);
704 newGame.vname = this.getVname(game.vid);
705 newGame.priority = 0;
706 if (!game.score)
707 // New game from Hall
708 newGame.score = "*";
709 if (newGame.score == "*") newGame.priority++;
710 newGame.rids = [game.rid];
711 delete newGame["rid"];
712 this.games.push(newGame);
713 if (
714 (newGame.type == "live" && this.gdisplay == "corr") ||
715 (newGame.type == "corr" && this.gdisplay == "live")
716 ) {
717 document
718 .getElementById("btnG" + newGame.type)
719 .classList.add("somethingnew");
720 }
721 } else {
722 // Append rid (if not already in list)
723 if (!locGame.rids.includes(game.rid)) locGame.rids.push(game.rid);
724 }
725 }
726 break;
727 }
728 case "result": {
729 let g = this.games.find(g => g.id == data.gid);
730 if (!!g) {
731 g.score = data.score;
732 g.priority = 0;
733 }
734 break;
735 }
736 case "startgame": {
737 // New game just started, I'm involved
738 const gameInfo = data.data;
739 if (this.classifyObject(gameInfo) == "live")
740 this.startNewGame(gameInfo);
741 else {
742 this.infoMessage =
743 this.st.tr["New correspondance game:"] +
744 " <a href='#/game/" +
745 gameInfo.id +
746 "'>" +
747 "#/game/" +
748 gameInfo.id +
749 "</a>";
750 document.getElementById("modalInfo").checked = true;
751 }
752 break;
753 }
754 case "newchat":
755 this.newChat = data.data;
756 if (!document.getElementById("modalPeople").checked)
757 document.getElementById("peopleBtn").classList.add("somethingnew");
758 break;
759 }
760 },
761 socketCloseListener: function() {
762 if (!this.conn) return;
763 this.conn = new WebSocket(this.connexionString);
764 this.conn.addEventListener("message", this.socketMessageListener);
765 this.conn.addEventListener("close", this.socketCloseListener);
766 },
767 // Challenge lifecycle:
768 loadNewchallVariant: async function(cb) {
769 const vname = this.getVname(this.newchallenge.vid);
770 const vModule = await import("@/variants/" + vname + ".js");
771 this.newchallenge.V = vModule.VariantRules;
772 this.newchallenge.vname = vname;
773 if (!!cb)
774 cb();
775 },
776 trySetNewchallDiag: function() {
777 if (!this.newchallenge.fen) {
778 this.newchallenge.diag = "";
779 return;
780 }
781 // If vid > 0 then the variant is loaded (function above):
782 window.V = this.newchallenge.V;
783 if (
784 this.newchallenge.vid > 0 &&
785 !!this.newchallenge.fen &&
786 V.IsGoodFen(this.newchallenge.fen)
787 ) {
788 const parsedFen = V.ParseFen(this.newchallenge.fen);
789 this.newchallenge.diag = getDiagram({
790 position: parsedFen.position,
791 orientation: parsedFen.turn
792 });
793 }
794 },
795 newChallenge: async function() {
796 if (!!(this.newchallenge.cadence.match(/^[0-9]+$/)))
797 this.newchallenge.cadence += "+0"; //assume minutes, no increment
798 const ctype = this.classifyObject(this.newchallenge);
799 // TODO: cadence still unchecked so ctype could be wrong...
800 let error = "";
801 if (!this.newchallenge.vid)
802 error = this.st.tr["Please select a variant"];
803 else if (ctype == "corr" && this.st.user.id <= 0)
804 error = this.st.tr["Please log in to play correspondance games"];
805 else if (!!this.newchallenge.to) {
806 if (this.newchallenge.to == this.st.user.name)
807 error = this.st.tr["Self-challenge is forbidden"];
808 else if (
809 ctype == "live" &&
810 Object.values(this.people).every(p => p.name != this.newchallenge.to)
811 )
812 error = this.newchallenge.to + " " + this.st.tr["is not online"];
813 }
814 if (error) {
815 alert(error);
816 return;
817 }
818 window.V = this.newchallenge.V;
819 error = checkChallenge(this.newchallenge);
820 if (error) {
821 alert(error);
822 return;
823 }
824 // NOTE: "from" information is not required here
825 let chall = Object.assign({}, this.newchallenge);
826 delete chall["V"];
827 delete chall["diag"];
828 const finishAddChallenge = cid => {
829 chall.id = cid || "c" + getRandString();
830 // Remove old challenge if any (only one at a time of a given type):
831 const cIdx = this.challenges.findIndex(
832 c =>
833 (c.from.sid == this.st.user.sid || c.from.id == this.st.user.id) &&
834 c.type == ctype
835 );
836 if (cIdx >= 0) {
837 // Delete current challenge (will be replaced now)
838 this.send("deletechallenge", { data: this.challenges[cIdx].id });
839 if (ctype == "corr") {
840 ajax(
841 "/challenges",
842 "DELETE",
843 { data: { id: this.challenges[cIdx].id } }
844 );
845 }
846 this.challenges.splice(cIdx, 1);
847 }
848 this.send("newchallenge", {
849 data: Object.assign({ from: this.st.user.sid }, chall)
850 });
851 // Add new challenge:
852 chall.from = {
853 // Decompose to avoid revealing email
854 sid: this.st.user.sid,
855 id: this.st.user.id,
856 name: this.st.user.name
857 };
858 chall.added = Date.now();
859 // NOTE: vname and type are redundant (can be deduced from cadence + vid)
860 chall.type = ctype;
861 chall.vname = this.newchallenge.vname;
862 this.challenges.push(chall);
863 // Remember cadence + vid for quicker further challenges:
864 localStorage.setItem("cadence", chall.cadence);
865 localStorage.setItem("vid", chall.vid);
866 localStorage.setItem("randomness", chall.randomness);
867 document.getElementById("modalNewgame").checked = false;
868 // Show the challenge if not on current display
869 if (
870 (ctype == "live" && this.cdisplay == "corr") ||
871 (ctype == "corr" && this.cdisplay == "live")
872 ) {
873 this.setDisplay('c', ctype);
874 }
875 };
876 if (ctype == "live") {
877 // Live challenges have a random ID
878 finishAddChallenge(null);
879 } else {
880 // Correspondance game: send challenge to server
881 ajax(
882 "/challenges",
883 "POST",
884 {
885 data: { chall: chall },
886 success: (response) => {
887 finishAddChallenge(response.cid);
888 }
889 }
890 );
891 }
892 },
893 // Callback function after a diagram was showed to accept
894 // or refuse targetted challenge:
895 decisionChallenge: function(accepted) {
896 this.curChallToAccept.accepted = accepted;
897 this.finishProcessingChallenge(this.curChallToAccept);
898 document.getElementById("modalAccept").checked = false;
899 },
900 finishProcessingChallenge: function(c) {
901 if (c.accepted) {
902 c.seat = {
903 // Again, avoid c.seat = st.user to not reveal email
904 sid: this.st.user.sid,
905 id: this.st.user.id,
906 name: this.st.user.name
907 };
908 this.launchGame(c);
909 } else {
910 const oppsid = this.getOppsid(c);
911 if (!!oppsid)
912 this.send("refusechallenge", { data: c.id, target: oppsid });
913 if (c.type == "corr") {
914 ajax(
915 "/challenges",
916 "DELETE",
917 { data: { id: c.id } }
918 );
919 }
920 }
921 this.send("deletechallenge", { data: c.id });
922 },
923 // TODO: if several players click same challenge at the same time: problem
924 clickChallenge: async function(c) {
925 const myChallenge =
926 c.from.sid == this.st.user.sid || //live
927 (this.st.user.id > 0 && c.from.id == this.st.user.id); //corr
928 if (!myChallenge) {
929 if (c.type == "corr" && this.st.user.id <= 0) {
930 alert(this.st.tr["Please log in to accept corr challenges"]);
931 return;
932 }
933 c.accepted = true;
934 const vModule = await import("@/variants/" + c.vname + ".js");
935 window.V = vModule.VariantRules;
936 if (!!c.to) {
937 // c.to == this.st.user.name (connected)
938 if (!!c.fen) {
939 const parsedFen = V.ParseFen(c.fen);
940 c.mycolor = V.GetOppCol(parsedFen.turn);
941 this.tchallDiag = getDiagram({
942 position: parsedFen.position,
943 orientation: c.mycolor
944 });
945 }
946 this.curChallToAccept = c;
947 document.getElementById("modalAccept").checked = true;
948 }
949 else this.finishProcessingChallenge(c);
950 }
951 else {
952 // My challenge
953 if (c.type == "corr") {
954 ajax(
955 "/challenges",
956 "DELETE",
957 { data: { id: c.id } }
958 );
959 }
960 this.send("deletechallenge", { data: c.id });
961 }
962 // In all cases, the challenge is consumed:
963 ArrayFun.remove(this.challenges, ch => ch.id == c.id);
964 },
965 // NOTE: when launching game, the challenge is already being deleted
966 launchGame: function(c) {
967 let players =
968 !!c.mycolor
969 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
970 : shuffle([c.from, c.seat]);
971 // Convention for players IDs in stored games is 'uid'
972 players.forEach(p => {
973 let pWithUid = p;
974 pWithUid["uid"] = p.id;
975 delete pWithUid["id"];
976 });
977 // These game informations will be shared
978 let gameInfo = {
979 id: getRandString(),
980 fen: c.fen || V.GenRandInitFen(c.randomness),
981 // White player index 0, black player index 1:
982 players: c.mycolor
983 ? (c.mycolor == "w" ? [c.seat, c.from] : [c.from, c.seat])
984 : shuffle([c.from, c.seat]),
985 vid: c.vid,
986 cadence: c.cadence
987 };
988 const notifyNewgame = () => {
989 const oppsid = this.getOppsid(c);
990 if (!!oppsid)
991 // Opponent is online
992 this.send("startgame", { data: gameInfo, target: oppsid });
993 // Send game info (only if live) to everyone except me and opponent
994 // TODO: this double message send could be avoided.
995 this.send("newgame", { data: gameInfo, oppsid: oppsid });
996 // Also to MyGames page:
997 this.send(
998 "notifynewgame",
999 {
1000 data: gameInfo,
1001 targets: gameInfo.players.map(p => {
1002 return { sid: p.sid, uid: p.uid };
1003 })
1004 }
1005 );
1006 };
1007 if (c.type == "live") {
1008 notifyNewgame();
1009 this.startNewGame(gameInfo);
1010 } else {
1011 // corr: game only on server
1012 ajax(
1013 "/games",
1014 "POST",
1015 {
1016 // cid is useful to delete the challenge:
1017 data: { gameInfo: gameInfo, cid: c.id },
1018 success: (response) => {
1019 gameInfo.id = response.gameId;
1020 notifyNewgame();
1021 this.$router.push("/game/" + response.gameId);
1022 }
1023 }
1024 );
1025 }
1026 },
1027 // NOTE: for live games only (corr games start on the server)
1028 startNewGame: function(gameInfo) {
1029 const game = Object.assign(
1030 {},
1031 gameInfo,
1032 {
1033 // (other) Game infos: constant
1034 fenStart: gameInfo.fen,
1035 vname: this.getVname(gameInfo.vid),
1036 created: Date.now(),
1037 // Game state (including FEN): will be updated
1038 moves: [],
1039 clocks: [-1, -1], //-1 = unstarted
1040 initime: [0, 0], //initialized later
1041 score: "*"
1042 }
1043 );
1044 setTimeout(
1045 () => {
1046 GameStorage.add(game, (err) => {
1047 // If an error occurred, game is not added: a tab already
1048 // added the game and (if focused) is redirected toward it.
1049 // If no error and the tab is hidden: do not show anything.
1050 if (!err && !document.hidden) {
1051 if (this.st.settings.sound)
1052 new Audio("/sounds/newgame.flac").play().catch(() => {});
1053 this.$router.push("/game/" + gameInfo.id);
1054 }
1055 });
1056 },
1057 document.hidden ? 500 + 1000 * Math.random() : 0
1058 );
1059 }
1060 }
1061 };
1062 </script>
1063
1064 <style lang="sass" scoped>
1065 .active
1066 color: #42a983
1067
1068 #infoDiv > .card
1069 padding: 15px 0
1070 max-width: 430px
1071
1072 #newgameDiv > .card, #acceptDiv > .card
1073 max-width: 767px
1074 max-height: 100%
1075
1076 div#peopleWrap > .card
1077 max-height: 100%
1078
1079 @media screen and (min-width: 1281px)
1080 div#peopleWrap > .card
1081 max-width: 66.67%
1082
1083 @media screen and (max-width: 1280px)
1084 div#peopleWrap > .card
1085 max-width: 83.33%
1086
1087 @media screen and (max-width: 767px)
1088 div#peopleWrap > .card
1089 max-width: 100%
1090
1091 #players
1092 width: 50%
1093 position: relative
1094 float: left
1095
1096 #chat
1097 width: 50%
1098 float: left
1099 position: relative
1100
1101 @media screen and (max-width: 767px)
1102 #players, #chats
1103 width: 100%
1104
1105 #chat > .card
1106 max-width: 100%
1107 margin: 0;
1108 border: none;
1109
1110 #players > p
1111 margin-left: 5px
1112
1113 .anonymous
1114 font-style: italic
1115
1116 button.player-action
1117 margin-left: 32px
1118
1119 .somethingnew
1120 background-color: #c5fefe !important
1121
1122 .tabbtn
1123 background-color: #f9faee
1124
1125 button.acceptBtn
1126 background-color: lightgreen
1127 button.refuseBtn
1128 background-color: red
1129
1130 #buttonsTchall
1131 // margin-top set dynamically (depends if diagram showed or not)
1132 & > button > span
1133 width: 100%
1134 text-align: center
1135
1136 .variantName
1137 font-weight: bold
1138
1139 .diagram
1140 margin: 0 auto
1141 max-width: 400px
1142 // width: 100% required for Firefox
1143 width: 100%
1144
1145 #inputFen
1146 width: 100%
1147
1148 #div2, #div3
1149 margin-top: 15px
1150 @media screen and (max-width: 767px)
1151 #div2, #div3
1152 margin-top: 0
1153 </style>