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