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