Typo
[vchess.git] / client / src / views / Game.vue
1 <template lang="pug">
2 main
3 input#modalRules.modal(type="checkbox")
4 div#rulesDiv(
5 role="dialog"
6 data-checkbox="modalRules"
7 )
8 .card
9 label.modal-close(for="modalRules")
10 a#variantNameInGame(:href="'/#/variants/'+game.vname") {{ game.vdisp }}
11 div(v-html="rulesContent")
12 input#modalScore.modal(type="checkbox")
13 div#scoreDiv(
14 role="dialog"
15 data-checkbox="modalScore"
16 )
17 .card.text-center
18 label.modal-close(for="modalScore")
19 p.score-section
20 span.score {{ game.score }}
21 | &nbsp;:&nbsp;
22 span.score-msg {{ st.tr[game.scoreMsg] }}
23 input#modalRematch.modal(type="checkbox")
24 div#rematchDiv(
25 role="dialog"
26 data-checkbox="modalRematch"
27 )
28 .card.text-center
29 label.modal-close(for="modalRematch")
30 a(
31 :href="'#/game/' + rematchId"
32 onClick="document.getElementById('modalRematch').checked=false"
33 )
34 | {{ st.tr["Rematch in progress"] }}
35 input#modalChat.modal(
36 type="checkbox"
37 @click="toggleChat()"
38 )
39 div#chatWrap(
40 role="dialog"
41 data-checkbox="modalChat"
42 )
43 .card
44 label.modal-close(for="modalChat")
45 #participants
46 span {{ st.tr["Participant(s):"] }}
47 span(
48 v-for="p in Object.values(people)"
49 v-if="!!p.name"
50 )
51 | {{ p.name }}
52 span.anonymous(v-if="someAnonymousPresent()") + @nonymous
53 Chat(
54 ref="chatcomp"
55 :players="game.players"
56 :pastChats="game.chats"
57 @mychat="processChat"
58 @chatcleared="clearChat"
59 )
60 input#modalConfirm.modal(type="checkbox")
61 div#confirmDiv(role="dialog")
62 .card
63 .diagram(
64 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
65 v-html="curDiag"
66 )
67 p.text-center(v-else)
68 span {{ st.tr["Move played:"] + " " }}
69 span.bold {{ moveNotation }}
70 br
71 span {{ st.tr["Are you sure?"] }}
72 .button-group#buttonsConfirm
73 // onClick for acceptBtn: set dynamically
74 button.acceptBtn
75 span {{ st.tr["Validate"] }}
76 button.refuseBtn(@click="cancelMove()")
77 span {{ st.tr["Cancel"] }}
78 .row
79 #aboveBoard.col-sm-12
80 span.variant-cadence(v-if="game.type!='import'") {{ game.cadence }}
81 span.variant-name {{ game.vname }}
82 span#nextGame(
83 v-if="nextIds.length > 0"
84 @click="showNextGame()"
85 )
86 | {{ st.tr["Next_g"] }}
87 button#chatBtn(
88 :class="btnTooltipClass()"
89 onClick="window.doClick('modalChat')"
90 aria-label="Chat"
91 )
92 img(src="/images/icons/chat.svg")
93 #actions(v-if="game.score=='*'")
94 button(
95 @click="clickDraw()"
96 :class="btnTooltipClass('draw')"
97 :aria-label="st.tr['Draw']"
98 )
99 img(src="/images/icons/draw.svg")
100 button(
101 v-if="!!game.mycolor"
102 :class="btnTooltipClass()"
103 @click="abortGame()"
104 :aria-label="st.tr['Abort']"
105 )
106 img(src="/images/icons/abort.svg")
107 button(
108 v-if="!!game.mycolor"
109 :class="btnTooltipClass()"
110 @click="resign()"
111 :aria-label="st.tr['Resign']"
112 )
113 img(src="/images/icons/resign.svg")
114 button(
115 v-else
116 :class="btnTooltipClass('rematch')"
117 @click="clickRematch()"
118 :aria-label="st.tr['Rematch']"
119 )
120 img(src="/images/icons/rematch.svg")
121 #playersInfo
122 div(v-if="isLargeScreen()")
123 UserBio.user-bio(
124 :class="{connected: isConnected(0)}"
125 :uid="game.players[0].id"
126 :uname="game.players[0].name"
127 )
128 span.time(
129 v-if="game.score=='*'"
130 :class="{yourturn: !!vr && vr.turn == 'w'}"
131 )
132 span.time-left {{ virtualClocks[0][0] }}
133 span.time-separator(v-if="!!virtualClocks[0][1]") :
134 span.time-right(v-if="!!virtualClocks[0][1]")
135 | {{ virtualClocks[0][1] }}
136 span.split-names -
137 UserBio.user-bio(
138 :class="{connected: isConnected(1)}"
139 :uid="game.players[1].id"
140 :uname="game.players[1].name"
141 )
142 span.time(
143 v-if="game.score=='*'"
144 :class="{yourturn: !!vr && vr.turn == 'b'}"
145 )
146 span.time-left {{ virtualClocks[1][0] }}
147 span.time-separator(v-if="!!virtualClocks[1][1]") :
148 span.time-right(v-if="!!virtualClocks[1][1]")
149 | {{ virtualClocks[1][1] }}
150 div(v-else)
151 UserBio.user-bio(
152 :class="{connected: isConnected(0)}"
153 :uid="game.players[0].id"
154 :uname="game.players[0].name"
155 )
156 span.split-names -
157 UserBio.user-bio(
158 :class="{connected: isConnected(1)}"
159 :uid="game.players[1].id"
160 :uname="game.players[1].name"
161 )
162 div(v-if="game.score=='*'")
163 span.time(:class="{yourturn: !!vr && vr.turn == 'w'}")
164 span.time-left {{ virtualClocks[0][0] }}
165 span.time-separator(v-if="!!virtualClocks[0][1]") :
166 span.time-right(v-if="!!virtualClocks[0][1]")
167 | {{ virtualClocks[0][1] }}
168 span.separator
169 span.time(:class="{yourturn: !!vr && vr.turn == 'b'}")
170 span.time-left {{ virtualClocks[1][0] }}
171 span.time-separator(v-if="!!virtualClocks[1][1]") :
172 span.time-right(v-if="!!virtualClocks[1][1]")
173 | {{ virtualClocks[1][1] }}
174 BaseGame(
175 ref="basegame"
176 :game="game"
177 @newmove="processMove"
178 )
179 </template>
180
181 <script>
182 import BaseGame from "@/components/BaseGame.vue";
183 import UserBio from "@/components/UserBio.vue";
184 import Chat from "@/components/Chat.vue";
185 import { store } from "@/store";
186 import { GameStorage } from "@/utils/gameStorage";
187 import { ImportgameStorage } from "@/utils/importgameStorage";
188 import { ppt } from "@/utils/datetime";
189 import { notify } from "@/utils/notifications";
190 import { ajax } from "@/utils/ajax";
191 import { extractTime } from "@/utils/timeControl";
192 import { getRandString } from "@/utils/alea";
193 import { getScoreMessage } from "@/utils/scoring";
194 import { getFullNotation } from "@/utils/notation";
195 import { getDiagram, replaceByDiag } from "@/utils/printDiagram";
196 import { processModalClick } from "@/utils/modalClick";
197 import { playMove, getFilteredMove } from "@/utils/playUndo";
198 import { ArrayFun } from "@/utils/array";
199 import afterRawLoad from "@/utils/afterRawLoad";
200 import params from "@/parameters";
201 export default {
202 name: "my-game",
203 components: {
204 BaseGame,
205 Chat,
206 UserBio
207 },
208 data: function() {
209 return {
210 st: store.state,
211 // gameRef can point to a corr game, local game or remote live game
212 gameRef: "",
213 nextIds: [],
214 game: {}, //passed to BaseGame
215 focus: !document.hidden, //will not always work... TODO
216 // virtualClocks will be initialized from true game.clocks
217 // TODO: clock update triggers re-rendering. Should be out of Vue
218 virtualClocks: [],
219 vr: null, //"variant rules" object initialized from FEN
220 rulesContent: "",
221 drawOffer: "",
222 rematchId: "",
223 rematchOffer: "",
224 lastateAsked: false,
225 people: {}, //players + observers
226 lastate: undefined, //used if opponent send lastate before game is ready
227 repeat: {}, //detect position repetition
228 curDiag: "", //for corr moves confirmation
229 conn: null,
230 roomInitialized: false,
231 // If asklastate got no reply, ask again:
232 gotLastate: false,
233 gotMoveIdx: -1, //last move index received
234 // If newmove got no pingback, send again:
235 opponentGotMove: false,
236 connexionString: "",
237 socketCloseListener: 0,
238 // Incomplete info games: show move played
239 moveNotation: "",
240 // Intervals from setInterval():
241 askLastate: null,
242 retrySendmove: null,
243 clockUpdate: null,
244 // Related to (killing of) self multi-connects:
245 newConnect: {}
246 };
247 },
248 watch: {
249 $route: function(to, from) {
250 if (to.path.length < 6 || to.path.substr(0, 6) != "/game/")
251 // Page change
252 this.cleanBeforeDestroy();
253 else if (from.params["id"] != to.params["id"]) {
254 // Change everything:
255 this.cleanBeforeDestroy();
256 let boardDiv = document.querySelector(".game");
257 if (!!boardDiv)
258 // In case of incomplete information variant:
259 boardDiv.style.visibility = "hidden";
260 this.atCreation();
261 }
262 else
263 // Same game ID
264 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
265 }
266 },
267 // NOTE: some redundant code with Hall.vue (mostly related to people array)
268 created: function() {
269 this.atCreation();
270 },
271 mounted: function() {
272 document.getElementById("chatWrap")
273 .addEventListener("click", (e) => {
274 processModalClick(e, () => {
275 this.toggleChat("close")
276 });
277 });
278 ["rulesDiv", "rematchDiv", "scoreDiv"].forEach(
279 (eltName) => {
280 document.getElementById(eltName)
281 .addEventListener("click", processModalClick);
282 }
283 );
284 },
285 beforeDestroy: function() {
286 this.cleanBeforeDestroy();
287 },
288 methods: {
289 cleanBeforeDestroy: function() {
290 clearInterval(this.socketCloseListener);
291 document.removeEventListener('visibilitychange', this.visibilityChange);
292 window.removeEventListener('focus', this.onFocus);
293 window.removeEventListener('blur', this.onBlur);
294 if (!!this.askLastate) clearInterval(this.askLastate);
295 if (!!this.retrySendmove) clearInterval(this.retrySendmove);
296 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
297 this.conn.removeEventListener("message", this.socketMessageListener);
298 this.send("disconnect");
299 this.conn = null;
300 },
301 visibilityChange: function() {
302 // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
303 this.focus = (document.visibilityState == "visible");
304 this.send(this.focus ? "getfocus" : "losefocus");
305 },
306 onFocus: function() {
307 this.focus = true;
308 this.send("getfocus");
309 },
310 onBlur: function() {
311 this.focus = false;
312 this.send("losefocus");
313 },
314 isLargeScreen: function() {
315 return window.innerWidth >= 768;
316 },
317 btnTooltipClass: function(thing) {
318 let append = {};
319 if (!!thing) append = { [thing + "-" + this[thing + "Offer"]]: true };
320 return (
321 Object.assign(
322 { tooltip: !("ontouchstart" in window) },
323 append
324 )
325 );
326 },
327 someAnonymousPresent: function() {
328 return (
329 Object.values(this.people).some(p =>
330 !p.name && Object.keys(p.tmpIds).some(x => p.tmpIds[x].focus)
331 )
332 );
333 },
334 atCreation: function() {
335 document.addEventListener('visibilitychange', this.visibilityChange);
336 window.addEventListener('focus', this.onFocus);
337 window.addEventListener('blur', this.onBlur);
338 // 0] (Re)Set variables
339 this.gameRef = this.$route.params["id"];
340 // next = next corr games IDs to navigate faster (if applicable)
341 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
342 // Always add myself to players' list
343 const my = this.st.user;
344 const tmpId = getRandString();
345 this.$set(
346 this.people,
347 my.sid,
348 {
349 id: my.id,
350 name: my.name,
351 tmpIds: {
352 tmpId: { focus: true }
353 }
354 }
355 );
356 this.game = {
357 players: [{ name: "" }, { name: "" }],
358 chats: [],
359 rendered: false
360 };
361 let chatComp = this.$refs["chatcomp"];
362 if (!!chatComp) chatComp.chats = [];
363 this.virtualClocks = [[0,0], [0,0]];
364 this.vr = null;
365 this.rulesContent = "";
366 this.drawOffer = "";
367 this.lastateAsked = false;
368 this.rematchOffer = "";
369 this.lastate = undefined;
370 this.roomInitialized = false;
371 this.gotLastate = false;
372 this.gotMoveIdx = -1;
373 this.opponentGotMove = false;
374 this.askLastate = null;
375 this.retrySendmove = null;
376 this.clockUpdate = null;
377 this.newConnect = {};
378 // 1] Initialize connection
379 this.connexionString =
380 params.socketUrl +
381 "/?sid=" + this.st.user.sid +
382 "&id=" + this.st.user.id +
383 "&tmpId=" + tmpId +
384 "&page=" +
385 // Discard potential "/?next=[...]" for page indication:
386 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
387 this.conn = new WebSocket(this.connexionString);
388 this.conn.addEventListener("message", this.socketMessageListener);
389 this.socketCloseListener = setInterval(
390 () => {
391 if (this.conn.readyState == 3) {
392 this.conn.removeEventListener(
393 "message", this.socketMessageListener);
394 this.conn = new WebSocket(this.connexionString);
395 this.conn.addEventListener("message", this.socketMessageListener);
396 }
397 },
398 1000
399 );
400 // Socket init required before loading remote game:
401 const socketInit = callback => {
402 if (this.conn.readyState == 1)
403 // 1 == OPEN state
404 callback();
405 else
406 // Socket not ready yet (initial loading)
407 // NOTE: first arg is Websocket object, unused here:
408 this.conn.onopen = () => callback();
409 };
410 this.fetchGame((game) => {
411 if (!!game)
412 this.loadVariantThenGame(game, () => socketInit(this.roomInit));
413 else
414 // Live game stored remotely: need socket to retrieve it
415 // NOTE: the callback "roomInit" will be lost, so it's not provided.
416 // --> It will be given when receiving "fullgame" socket event.
417 socketInit(() => { this.send("askfullgame"); });
418 });
419 },
420 roomInit: function() {
421 if (!this.roomInitialized) {
422 // Notify the room only now that I connected, because
423 // messages might be lost otherwise (if game loading is slow)
424 this.send("connect");
425 this.send("pollclients");
426 // We may ask fullgame several times if some moves are lost,
427 // but room should be init only once:
428 this.roomInitialized = true;
429 }
430 },
431 send: function(code, obj) {
432 if (!!this.conn && this.conn.readyState == 1)
433 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
434 },
435 isConnected: function(index) {
436 const player = this.game.players[index];
437 // Is it me ? In this case no need to bother with focus
438 if (
439 this.st.user.sid == player.sid ||
440 (!!player.name && this.st.user.id == player.id)
441 ) {
442 // Still have to check for name (because of potential multi-accounts
443 // on same browser, although this should be rare...)
444 return (!this.st.user.name || this.st.user.name == player.name);
445 }
446 // Try to find a match in people:
447 return (
448 (
449 !!player.sid &&
450 Object.keys(this.people).some(sid => {
451 return (
452 sid == player.sid &&
453 Object.values(this.people[sid].tmpIds).some(v => v.focus)
454 );
455 })
456 )
457 ||
458 (
459 player.id > 0 &&
460 Object.values(this.people).some(p => {
461 return (
462 p.id == player.id &&
463 Object.values(p.tmpIds).some(v => v.focus)
464 );
465 })
466 )
467 );
468 },
469 getOppsid: function() {
470 let oppsid = this.game.oppsid;
471 if (!oppsid) {
472 oppsid = Object.keys(this.people).find(
473 sid => this.people[sid].id == this.game.oppid
474 );
475 }
476 // oppsid is useful only if opponent is online:
477 if (!!oppsid && !!this.people[oppsid]) return oppsid;
478 return null;
479 },
480 // NOTE: action if provided is always a closing action
481 toggleChat: function(action) {
482 if (!action && document.getElementById("modalChat").checked)
483 // Entering chat
484 document.getElementById("inputChat").focus();
485 else {
486 document.getElementById("chatBtn").classList.remove("somethingnew");
487 if (!!this.game.mycolor) {
488 // Update "chatRead" variable either on server or locally
489 if (this.game.type == "corr")
490 this.updateCorrGame({ chatRead: this.game.mycolor });
491 else if (this.game.type == "live")
492 GameStorage.update(this.gameRef, { chatRead: true });
493 }
494 }
495 },
496 processChat: function(chat) {
497 this.send("newchat", { data: chat });
498 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
499 if (!!this.game.mycolor) {
500 if (this.game.type == "corr")
501 this.updateCorrGame({ chat: chat });
502 else {
503 // Live game
504 chat.added = Date.now();
505 GameStorage.update(this.gameRef, { chat: chat });
506 }
507 }
508 },
509 clearChat: function() {
510 if (!!this.game.mycolor) {
511 if (this.game.type == "corr") {
512 ajax(
513 "/chats",
514 "DELETE",
515 { data: { gid: this.game.id } }
516 );
517 }
518 else {
519 // Live game
520 GameStorage.update(this.gameRef, { delchat: true });
521 }
522 this.$set(this.game, "chats", []);
523 }
524 },
525 getGameType: function(game) {
526 if (!!game.id.toString().match(/^i/)) return "import";
527 return (game.cadence.indexOf("d") >= 0 ? "corr" : "live");
528 },
529 // Notify something after a new move (to opponent and me on MyGames page)
530 notifyMyGames: function(thing, data) {
531 this.send(
532 "notify" + thing,
533 {
534 data: data,
535 targets: this.game.players.map(p => {
536 return { sid: p.sid, id: p.id };
537 })
538 }
539 );
540 },
541 showNextGame: function() {
542 // Did I play in current game? If not, add it to nextIds list
543 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
544 this.nextIds.unshift(this.game.id);
545 const nextGid = this.nextIds.pop();
546 this.$router.push(
547 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
548 },
549 socketMessageListener: function(msg) {
550 if (!this.conn) return;
551 const data = JSON.parse(msg.data);
552 switch (data.code) {
553 case "pollclients":
554 // TODO: shuffling and random filtering on server,
555 // if the room is really crowded.
556 Object.keys(data.sockIds).forEach(sid => {
557 if (sid != this.st.user.sid) {
558 this.send("askidentity", { target: sid });
559 this.people[sid] = { tmpIds: data.sockIds[sid] };
560 }
561 else {
562 // Complete my tmpIds:
563 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
564 }
565 });
566 break;
567 case "connect":
568 if (!this.people[data.from[0]]) {
569 // focus depends on the tmpId (e.g. tab)
570 this.$set(
571 this.people,
572 data.from[0],
573 {
574 tmpIds: {
575 [data.from[1]]: { focus: true }
576 }
577 }
578 );
579 // For self multi-connects tests:
580 this.newConnect[data.from[0]] = true;
581 this.send("askidentity", { target: data.from[0] });
582 }
583 else {
584 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
585 this.$forceUpdate(); //TODO: shouldn't be required
586 }
587 break;
588 case "disconnect":
589 if (!this.people[data.from[0]]) return;
590 delete this.people[data.from[0]].tmpIds[data.from[1]];
591 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
592 this.$delete(this.people, data.from[0]);
593 else this.$forceUpdate(); //TODO: shouldn't be required
594 break;
595 case "getfocus": {
596 let player = this.people[data.from[0]];
597 if (!!player) {
598 player.tmpIds[data.from[1]].focus = true;
599 this.$forceUpdate(); //TODO: shouldn't be required
600 }
601 break;
602 }
603 case "losefocus": {
604 let player = this.people[data.from[0]];
605 if (!!player) {
606 player.tmpIds[data.from[1]].focus = false;
607 this.$forceUpdate(); //TODO: shouldn't be required
608 }
609 break;
610 }
611 case "askidentity": {
612 // Request for identification
613 const me = {
614 // Decompose to avoid revealing email
615 name: this.st.user.name,
616 sid: this.st.user.sid,
617 id: this.st.user.id
618 };
619 this.send("identity", { data: me, target: data.from });
620 break;
621 }
622 case "identity": {
623 const user = data.data;
624 let player = this.people[user.sid];
625 // player.tmpIds is already set
626 player.name = user.name;
627 player.id = user.id;
628 if (this.game.type == "live") {
629 const myGidx =
630 this.game.players.findIndex(p => p.sid == this.st.user.sid);
631 // Sometimes a player name isn't stored yet (TODO: why?)
632 if (
633 myGidx >= 0 &&
634 !this.game.players[1 - myGidx].name &&
635 this.game.players[1 - myGidx].sid == user.sid &&
636 !!user.name
637 ) {
638 this.game.players[1-myGidx].name = user.name;
639 GameStorage.update(
640 this.gameRef,
641 { playerName: { idx: 1 - myGidx, name: user.name } }
642 );
643 }
644 }
645 this.$forceUpdate(); //TODO: shouldn't be required
646 // If I multi-connect, kill current connexion if no mark (I'm older)
647 if (this.newConnect[user.sid]) {
648 delete this.newConnect[user.sid];
649 if (
650 user.id > 0 &&
651 user.id == this.st.user.id &&
652 user.sid != this.st.user.sid
653 ) {
654 this.cleanBeforeDestroy();
655 alert(this.st.tr["New connexion detected: tab now offline"]);
656 break;
657 }
658 }
659 // Ask potentially missed last state, if opponent and I play
660 if (
661 !this.gotLastate &&
662 !!this.game.mycolor &&
663 this.game.type == "live" &&
664 this.game.players.some(p => p.sid == user.sid)
665 ) {
666 this.send("asklastate", { target: user.sid });
667 let counter = 1;
668 this.askLastate = setInterval(
669 () => {
670 // Ask at most 3 times:
671 // if no reply after that there should be a network issue.
672 if (
673 counter < 3 &&
674 !this.gotLastate &&
675 !!this.people[user.sid]
676 ) {
677 this.send("asklastate", { target: user.sid });
678 counter++;
679 }
680 else clearInterval(this.askLastate);
681 },
682 1500
683 );
684 }
685 break;
686 }
687 case "askgame":
688 // Send current (live or import) game,
689 // if not asked by any of the players
690 if (
691 this.game.type != "corr" &&
692 this.game.players.every(p => p.sid != data.from[0])
693 ) {
694 const myGame = {
695 id: this.game.id,
696 // FEN is current position, unused for now
697 fen: this.game.fen,
698 players: this.game.players,
699 vid: this.game.vid,
700 cadence: this.game.cadence,
701 score: this.game.score
702 };
703 this.send("game", { data: myGame, target: data.from });
704 }
705 break;
706 case "askfullgame":
707 const gameToSend = Object.keys(this.game)
708 .filter(k =>
709 [
710 "id","fen","players","vid","cadence","fenStart",
711 "moves","clocks","score","drawOffer","rematchOffer"
712 ].includes(k))
713 .reduce(
714 (obj, k) => {
715 obj[k] = this.game[k];
716 return obj;
717 },
718 {}
719 );
720 this.send("fullgame", { data: gameToSend, target: data.from });
721 break;
722 case "fullgame":
723 if (!!data.data.empty) {
724 alert(this.st.tr["The game should be in another tab"]);
725 this.$router.go(-1);
726 }
727 else
728 // Callback "roomInit" to poll clients only after game is loaded
729 this.loadVariantThenGame(data.data, this.roomInit);
730 break;
731 case "asklastate":
732 // Sending informative last state if I played a move or score != "*"
733 // If the game or moves aren't loaded yet, delay the sending:
734 // TODO: socket init after game load, so the game is supposedly ready
735 if (!this.game || !this.game.moves) this.lastateAsked = true;
736 else this.sendLastate(data.from);
737 break;
738 // TODO: possible bad scenario: reload page while oppponent sends a
739 // move => get both lastate and newmove, process both, add move twice.
740 // Confirm scenario? Fix?
741 case "lastate": {
742 // Got opponent infos about last move
743 this.gotLastate = true;
744 this.lastate = data.data;
745 if (this.lastate.movesCount - 1 > this.gotMoveIdx)
746 this.gotMoveIdx = this.lastate.movesCount - 1;
747 if (this.game.rendered)
748 // Game is rendered (Board component)
749 this.processLastate();
750 // Else: will be processed when game is ready
751 break;
752 }
753 case "newmove": {
754
755 // DEBUG:
756 //console.log("Receive move");
757 //console.log(data.data);
758 //moveslist not updated when receiving a move? (see in BaseGame)
759
760 const movePlus = data.data;
761 const movesCount = this.game.moves.length;
762 if (
763 movePlus.index < movesCount ||
764 this.gotMoveIdx >= movePlus.index
765 ) {
766 // Opponent re-send but we already have the move:
767 // (maybe he didn't receive our pingback...)
768 this.send("gotmove", {data: movePlus.index, target: data.from});
769 }
770 else {
771 this.gotMoveIdx = movePlus.index;
772 const receiveMyMove = (movePlus.color == this.game.mycolor);
773 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
774 if (!receiveMyMove && !!this.game.mycolor) {
775 // Notify opponent that I got the move:
776 this.send(
777 "gotmove",
778 { data: movePlus.index, target: data.from }
779 );
780 // And myself if I'm elsewhere:
781 if (!this.focus) {
782 notify(
783 "New move",
784 {
785 body:
786 (this.game.players[moveColIdx].name || "@nonymous") +
787 " just played."
788 }
789 );
790 }
791 }
792 if (movePlus.cancelDrawOffer) {
793 // Opponent refuses draw
794 this.drawOffer = "";
795 // NOTE for corr games: drawOffer reset by player in turn
796 if (
797 this.game.type == "live" &&
798 !!this.game.mycolor &&
799 !receiveMyMove
800 ) {
801 GameStorage.update(this.gameRef, { drawOffer: "" });
802 }
803 }
804 this.$refs["basegame"].play(movePlus.move, "received");
805 // Freeze time while the move is being play
806 // (TODO: a callback would be cleaner here)
807 clearInterval(this.clockUpdate);
808 this.clockUpdate = null;
809 const freezeDuration = ["all", "highlight"].includes(V.ShowMoves)
810 // 250 = length of animation, 500 = delay between sub-moves
811 ? 250 + 750 *
812 (Array.isArray(movePlus.move) ? movePlus.move.length - 1 : 0)
813 // Incomplete information: no move animation
814 : 0;
815 setTimeout(
816 () => {
817 this.game.clocks[moveColIdx] = movePlus.clock;
818 this.processMove(
819 movePlus.move,
820 { receiveMyMove: receiveMyMove }
821 );
822 },
823 freezeDuration
824 );
825 }
826 break;
827 }
828 case "gotmove": {
829 this.opponentGotMove = true;
830 // Now his clock starts running on my side:
831 const oppIdx = ['w','b'].indexOf(this.vr.turn);
832 // NOTE: next line to avoid multi-resetClocks when several tabs
833 // on same game, resulting in a faster countdown.
834 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
835 this.re_setClocks();
836 break;
837 }
838 case "resign":
839 const score = (data.data == "b" ? "1-0" : "0-1");
840 const side = (data.data == "w" ? "White" : "Black");
841 this.gameOver(score, side + " surrender");
842 break;
843 case "abort":
844 this.gameOver("?", "Stop");
845 break;
846 case "draw":
847 this.gameOver("1/2", data.data);
848 break;
849 case "drawoffer":
850 // NOTE: observers don't know who offered draw
851 this.drawOffer = "received";
852 if (!!this.game.mycolor && this.game.type == "live") {
853 GameStorage.update(
854 this.gameRef,
855 { drawOffer: V.GetOppCol(this.game.mycolor) }
856 );
857 }
858 break;
859 case "rematchoffer":
860 // NOTE: observers don't know who offered rematch
861 this.rematchOffer = data.data ? "received" : "";
862 if (!!this.game.mycolor && this.game.type == "live") {
863 GameStorage.update(
864 this.gameRef,
865 { rematchOffer: data.data ? V.GetOppCol(this.game.mycolor) : "" }
866 );
867 }
868 break;
869 case "newgame": {
870 // A game started, redirect if I'm playing in
871 const gameInfo = data.data;
872 const gameType = this.getGameType(gameInfo);
873 if (
874 gameType == "live" &&
875 gameInfo.players.some(p => p.sid == this.st.user.sid)
876 ) {
877 this.addAndGotoLiveGame(gameInfo);
878 }
879 else if (
880 gameType == "corr" &&
881 this.st.user.id > 0 &&
882 gameInfo.players.some(p => p.id == this.st.user.id)
883 ) {
884 this.$router.push("/game/" + gameInfo.id);
885 }
886 else {
887 this.rematchId = gameInfo.id;
888 document.getElementById("modalRules").checked = false;
889 document.getElementById("modalScore").checked = false;
890 document.getElementById("modalRematch").checked = true;
891 }
892 break;
893 }
894 case "newchat": {
895 let chat = data.data;
896 this.$refs["chatcomp"].newChat(chat);
897 if (this.game.type == "live") {
898 chat.added = Date.now();
899 if (!!this.game.mycolor)
900 GameStorage.update(this.gameRef, { chat: chat });
901 }
902 if (!document.getElementById("modalChat").checked)
903 document.getElementById("chatBtn").classList.add("somethingnew");
904 break;
905 }
906 }
907 },
908 updateCorrGame: function(obj, callback) {
909 ajax(
910 "/games",
911 "PUT",
912 {
913 data: {
914 gid: this.gameRef,
915 newObj: obj
916 },
917 success: () => {
918 if (!!callback) callback();
919 }
920 }
921 );
922 },
923 sendLastate: function(target) {
924 // Send our "last state" informations to opponent
925 const L = this.game.moves.length;
926 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
927 const myLastate = {
928 lastMove:
929 (L > 0 && this.vr.turn != this.game.mycolor)
930 ? this.game.moves[L - 1]
931 : undefined,
932 clock: this.game.clocks[myIdx],
933 // Since we played a move (or abort or resign),
934 // only drawOffer=="sent" is possible
935 drawSent: this.drawOffer == "sent" ? true : undefined,
936 rematchSent: this.rematchOffer == "sent" ? true : undefined,
937 score: this.game.score != "*" ? this.game.score : undefined,
938 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
939 movesCount: L
940 };
941 this.send("lastate", { data: myLastate, target: target });
942 },
943 // lastate was received, but maybe game wasn't ready yet:
944 processLastate: function() {
945 const data = this.lastate;
946 this.lastate = undefined; //security...
947 if (!!data.score) {
948 const oppCol = V.GetOppCol(this.game.mycolor);
949 if (!!data.rematchSent) {
950 if (this.game.rematchOffer != oppCol) {
951 // Opponent sended rematch offer while we were offline:
952 this.rematchOffer = "received";
953 GameStorage.update(
954 this.gameRef,
955 { rematchOffer: oppCol }
956 );
957 }
958 }
959 else {
960 if (this.game.rematchOffer == oppCol) {
961 // Opponent cancelled rematch offer while we were offline:
962 this.rematchOffer = "";
963 GameStorage.update(
964 this.gameRef,
965 { rematchOffer: "" }
966 );
967 }
968 }
969 }
970 else {
971 const L = this.game.moves.length;
972 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
973 this.game.clocks[oppIdx] = data.clock;
974 if (data.movesCount > L) {
975 // Just got last move from him
976 this.$refs["basegame"].play(data.lastMove, "received");
977 this.processMove(data.lastMove);
978 }
979 else {
980 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
981 this.re_setClocks();
982 }
983 if (!!data.drawSent) this.drawOffer = "received";
984 if (!!data.score) {
985 this.drawOffer = "";
986 if (this.game.score == "*")
987 this.gameOver(data.score, data.scoreMsg);
988 }
989 }
990 },
991 clickDraw: function() {
992 if (!this.game.mycolor || this.game.type == "import") return;
993 if (["received", "threerep"].includes(this.drawOffer)) {
994 if (!confirm(this.st.tr["Accept draw?"])) return;
995 const message =
996 this.drawOffer == "received"
997 ? "Mutual agreement"
998 : "Three repetitions";
999 this.send("draw", { data: message });
1000 this.gameOver("1/2", message);
1001 }
1002 else if (this.drawOffer == "") {
1003 // No effect if drawOffer == "sent"
1004 if (this.game.mycolor != this.vr.turn) {
1005 alert(this.st.tr["Draw offer only in your turn"]);
1006 return;
1007 }
1008 if (!confirm(this.st.tr["Offer draw?"])) return;
1009 this.drawOffer = "sent";
1010 this.send("drawoffer");
1011 if (this.game.type == "live") {
1012 GameStorage.update(
1013 this.gameRef,
1014 { drawOffer: this.game.mycolor }
1015 );
1016 }
1017 else this.updateCorrGame({ drawOffer: this.game.mycolor });
1018 }
1019 },
1020 addAndGotoLiveGame: function(gameInfo, callback) {
1021 const game = Object.assign(
1022 {},
1023 gameInfo,
1024 {
1025 // (other) Game infos: constant
1026 fenStart: gameInfo.fen,
1027 created: Date.now(),
1028 // Game state (including FEN): will be updated
1029 moves: [],
1030 clocks: [-1, -1], //-1 = unstarted
1031 chats: [],
1032 score: "*"
1033 }
1034 );
1035 GameStorage.add(game, (err) => {
1036 // No error expected.
1037 if (!err) {
1038 if (this.st.settings.sound)
1039 new Audio("/sounds/newgame.flac").play().catch(() => {});
1040 if (!!callback) callback();
1041 this.$router.push("/game/" + gameInfo.id);
1042 }
1043 });
1044 },
1045 clickRematch: function() {
1046 if (!this.game.mycolor || this.game.type == "import") return;
1047 if (this.rematchOffer == "received") {
1048 // Start a new game!
1049 let gameInfo = {
1050 id: getRandString(), //ignored if corr
1051 fen: V.GenRandInitFen(this.game.randomness),
1052 randomness: this.game.randomness,
1053 players: [this.game.players[1], this.game.players[0]],
1054 vid: this.game.vid,
1055 cadence: this.game.cadence
1056 };
1057 const notifyNewGame = () => {
1058 this.send("rnewgame", { data: gameInfo });
1059 // To main Hall if corr game:
1060 if (this.game.type == "corr")
1061 this.send("newgame", { data: gameInfo, page: "/" });
1062 // Also to MyGames page:
1063 this.notifyMyGames("newgame", gameInfo);
1064 };
1065 if (this.game.type == "live") {
1066 GameStorage.update(
1067 this.gameRef,
1068 { rematchOffer: "" }
1069 );
1070 // Increment game stats counter in DB
1071 ajax(
1072 "/gamestat",
1073 "POST",
1074 { data: { vid: gameInfo.vid } }
1075 );
1076 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1077 }
1078 else {
1079 // corr game
1080 this.updateCorrGame({ rematchOffer: 'n' });
1081 ajax(
1082 "/games",
1083 "POST",
1084 {
1085 data: { gameInfo: gameInfo },
1086 success: (response) => {
1087 gameInfo.id = response.id;
1088 notifyNewGame();
1089 this.$router.push("/game/" + response.id);
1090 }
1091 }
1092 );
1093 }
1094 }
1095 else if (this.rematchOffer == "") {
1096 this.rematchOffer = "sent";
1097 this.send("rematchoffer", { data: true });
1098 if (this.game.type == "live") {
1099 GameStorage.update(
1100 this.gameRef,
1101 { rematchOffer: this.game.mycolor }
1102 );
1103 }
1104 else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1105 }
1106 else if (this.rematchOffer == "sent") {
1107 // Toggle rematch offer (on --> off)
1108 this.rematchOffer = "";
1109 this.send("rematchoffer", { data: false });
1110 if (this.game.type == "live") {
1111 GameStorage.update(
1112 this.gameRef,
1113 { rematchOffer: '' }
1114 );
1115 }
1116 else this.updateCorrGame({ rematchOffer: 'n' });
1117 }
1118 },
1119 abortGame: function() {
1120 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1121 return;
1122 this.gameOver("?", "Stop");
1123 this.send("abort");
1124 },
1125 resign: function() {
1126 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1127 return;
1128 this.send("resign", { data: this.game.mycolor });
1129 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1130 const side = (this.game.mycolor == "w" ? "White" : "Black");
1131 this.gameOver(score, side + " surrender");
1132 },
1133 loadGame: function(game, callback) {
1134 const gtype = game.type || this.getGameType(game);
1135 const tc = extractTime(game.cadence);
1136 const myIdx = game.players.findIndex(p => {
1137 return (
1138 p.sid == this.st.user.sid ||
1139 (!!p.name && p.id == this.st.user.id)
1140 );
1141 });
1142 // Sometimes the name isn't stored yet (TODO: why?)
1143 if (
1144 myIdx >= 0 &&
1145 gtype == "live" &&
1146 !game.players[myIdx].name &&
1147 !!this.st.user.name
1148 ) {
1149 game.players[myIdx].name = this.st.user.name;
1150 GameStorage.update(
1151 game.id,
1152 { playerName: { idx: myIdx, name: this.st.user.name } }
1153 );
1154 }
1155 // "mycolor" is undefined for observers
1156 const mycolor = [undefined, "w", "b"][myIdx + 1];
1157 if (gtype == "corr") {
1158 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1159 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1160 // NOTE: clocks in seconds
1161 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1162 game.clocks = [tc.mainTime, tc.mainTime];
1163 const L = game.moves.length;
1164 if (game.score == "*") {
1165 // Adjust clocks
1166 if (L >= 2) {
1167 game.clocks[L % 2] -=
1168 (Date.now() - game.moves[L-1].played) / 1000;
1169 }
1170 }
1171 // Now that we used idx and played, re-format moves as for live games
1172 game.moves = game.moves.map(m => m.squares);
1173 }
1174 else if (gtype == "live") {
1175 if (game.clocks[0] < 0) {
1176 // Game is unstarted. clock is ignored until move 2
1177 game.clocks = [tc.mainTime, tc.mainTime];
1178 if (myIdx >= 0) {
1179 // I play in this live game
1180 GameStorage.update(
1181 game.id,
1182 { clocks: game.clocks }
1183 );
1184 }
1185 }
1186 else if (!!game.initime)
1187 // It's my turn: clocks not updated yet
1188 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1189 }
1190 else
1191 // gtype == "import"
1192 game.clocks = [tc.mainTime, tc.mainTime];
1193 // Live games before 26/03/2020 don't have chat history:
1194 if (!game.chats) game.chats = []; //TODO: remove line
1195 // Sort chat messages from newest to oldest
1196 game.chats.sort((c1, c2) => c2.added - c1.added);
1197 if (
1198 myIdx >= 0 &&
1199 game.chats.length > 0 &&
1200 (!game.chatRead || game.chatRead < game.chats[0].added)
1201 ) {
1202 // A chat message arrived since my last reading:
1203 document.getElementById("chatBtn").classList.add("somethingnew");
1204 }
1205 // TODO: merge next 2 "if" conditions
1206 if (!!game.drawOffer) {
1207 if (game.drawOffer == "t")
1208 // Three repetitions
1209 this.drawOffer = "threerep";
1210 else {
1211 // Draw offered by any of the players:
1212 if (myIdx < 0) this.drawOffer = "received";
1213 else {
1214 // I play in this game:
1215 if (
1216 (game.drawOffer == "w" && myIdx == 0) ||
1217 (game.drawOffer == "b" && myIdx == 1)
1218 )
1219 this.drawOffer = "sent";
1220 else this.drawOffer = "received";
1221 }
1222 }
1223 }
1224 if (!!game.rematchOffer) {
1225 if (myIdx < 0) this.rematchOffer = "received";
1226 else {
1227 // I play in this game:
1228 if (
1229 (game.rematchOffer == "w" && myIdx == 0) ||
1230 (game.rematchOffer == "b" && myIdx == 1)
1231 ) {
1232 this.rematchOffer = "sent";
1233 }
1234 else this.rematchOffer = "received";
1235 }
1236 }
1237 this.repeat = {}; //reset: scan past moves' FEN:
1238 let repIdx = 0;
1239 this.vr = new V(game.fenStart);
1240 let curTurn = "n";
1241 game.moves.forEach(m => {
1242 playMove(m, this.vr);
1243 const fenIdx = this.vr.getFenForRepeat();
1244 this.repeat[fenIdx] = this.repeat[fenIdx]
1245 ? this.repeat[fenIdx] + 1
1246 : 1;
1247 });
1248 // Imported games don't have current FEN
1249 if (!game.fen) game.fen = this.vr.getFen();
1250 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1251 this.game = Object.assign(
1252 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1253 {
1254 type: gtype,
1255 increment: tc.increment,
1256 mycolor: mycolor,
1257 // opponent sid not strictly required (or available), but easier
1258 // at least oppsid or oppid is available anyway:
1259 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1260 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1261 },
1262 game
1263 );
1264 this.$refs["basegame"].re_setVariables(this.game);
1265 // Initial loading:
1266 this.gotMoveIdx = game.moves.length - 1;
1267 // If we arrive here after 'nextGame' action, the board might be hidden
1268 let boardDiv = document.querySelector(".game");
1269 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1270 boardDiv.style.visibility = "visible";
1271 this.re_setClocks();
1272 this.$nextTick(() => {
1273 this.game.rendered = true;
1274 // Did lastate arrive before game was rendered?
1275 if (!!this.lastate) this.processLastate();
1276 });
1277 if (this.lastateAsked) {
1278 this.lastateAsked = false;
1279 this.sendLastate(game.oppsid);
1280 }
1281 if (!!callback) callback();
1282 },
1283 loadVariantThenGame: async function(game, callback) {
1284 const afterSetVname = async () => {
1285 await import("@/variants/" + game.vname + ".js")
1286 .then((vModule) => {
1287 window.V = vModule[game.vname + "Rules"];
1288 this.loadGame(game, callback);
1289 });
1290 this.rulesContent =
1291 afterRawLoad(
1292 require(
1293 "raw-loader!@/translations/rules/" +
1294 game.vname + "/" + this.st.lang + ".pug"
1295 ).default
1296 ).replace(/(fen:)([^:]*):/g, replaceByDiag);
1297 };
1298 let variant = undefined;
1299 const trySetVname = setInterval(
1300 () => {
1301 // this.st.variants might be uninitialized (variant == null)
1302 variant = this.st.variants.find(v => v.id == game.vid);
1303 if (!!variant) {
1304 clearInterval(trySetVname);
1305 game.vname = variant.name;
1306 game.vdisp = variant.display;
1307 afterSetVname();
1308 }
1309 }, 500
1310 );
1311 },
1312 // 3 cases for loading a game:
1313 // - from indexedDB (running or completed live game I play)
1314 // - from server (one correspondance game I play[ed] or not)
1315 // - from remote peer (one live game I don't play, finished or not)
1316 fetchGame: function(callback) {
1317 if (
1318 Number.isInteger(this.gameRef) ||
1319 !isNaN(parseInt(this.gameRef, 10))
1320 ) {
1321 // corr games identifiers are integers
1322 ajax(
1323 "/games",
1324 "GET",
1325 {
1326 data: { gid: this.gameRef },
1327 success: (res) => {
1328 res.game.moves.forEach(m => {
1329 m.squares = JSON.parse(m.squares);
1330 });
1331 callback(res.game);
1332 }
1333 }
1334 );
1335 }
1336 else if (!!this.gameRef.match(/^i/))
1337 // Game import (maybe remote)
1338 ImportgameStorage.get(this.gameRef, callback);
1339 else
1340 // Local live game (or remote)
1341 GameStorage.get(this.gameRef, callback);
1342 },
1343 re_setClocks: function() {
1344 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1345 if (this.game.moves.length < 2 || this.game.score != "*") {
1346 // 1st move not completed yet, or game over: freeze time
1347 return;
1348 }
1349 const currentTurn = this.vr.turn;
1350 const currentMovesCount = this.game.moves.length;
1351 const colorIdx = ["w", "b"].indexOf(currentTurn);
1352 this.clockUpdate = setInterval(
1353 () => {
1354 if (
1355 this.game.clocks[colorIdx] < 0 ||
1356 this.game.moves.length > currentMovesCount ||
1357 this.game.score != "*"
1358 ) {
1359 clearInterval(this.clockUpdate);
1360 this.clockUpdate = null;
1361 if (this.game.clocks[colorIdx] < 0)
1362 this.gameOver(
1363 currentTurn == "w" ? "0-1" : "1-0",
1364 "Time"
1365 );
1366 }
1367 else {
1368 this.$set(
1369 this.virtualClocks,
1370 colorIdx,
1371 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1372 );
1373 }
1374 },
1375 1000
1376 );
1377 },
1378 // Update variables and storage after a move:
1379 processMove: function(move, data) {
1380 if (this.game.type == "import")
1381 // Shouldn't receive any messages in this mode:
1382 return;
1383 if (!data) data = {};
1384 const moveCol = this.vr.turn;
1385 const colorIdx = ["w", "b"].indexOf(moveCol);
1386 const nextIdx = 1 - colorIdx;
1387 const doProcessMove = () => {
1388 const origMovescount = this.game.moves.length;
1389 // The move is (about to be) played: stop clock
1390 clearInterval(this.clockUpdate);
1391 this.clockUpdate = null;
1392 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1393 if (this.drawOffer == "received")
1394 // I refuse draw
1395 this.drawOffer = "";
1396 if (this.game.type == "live" && origMovescount >= 2) {
1397 this.game.clocks[colorIdx] += this.game.increment;
1398 // For a correct display in casqe of disconnected opponent:
1399 this.$set(
1400 this.virtualClocks,
1401 colorIdx,
1402 ppt(this.game.clocks[colorIdx]).split(':')
1403 );
1404 GameStorage.update(this.gameRef, {
1405 // It's not my turn anymore:
1406 initime: null
1407 });
1408 }
1409 }
1410 // Update current game object:
1411 playMove(move, this.vr);
1412 if (!data.score)
1413 // Received move, score is computed in BaseGame, but maybe not yet.
1414 // ==> Compute it here, although this is redundant (TODO)
1415 data.score = this.vr.getCurrentScore();
1416 if (data.score != "*") this.gameOver(data.score);
1417 this.game.moves.push(move);
1418 this.game.fen = this.vr.getFen();
1419 if (this.game.type == "corr") {
1420 // In corr games, just reset clock to mainTime:
1421 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1422 }
1423 if (!V.IgnoreRepetition) {
1424 // If repetition detected, consider that a draw offer was received:
1425 const fenObj = this.vr.getFenForRepeat();
1426 this.repeat[fenObj] =
1427 !!this.repeat[fenObj]
1428 ? this.repeat[fenObj] + 1
1429 : 1;
1430 if (this.repeat[fenObj] >= 3) {
1431 if (this.vr.loseOnRepetition())
1432 this.gameOver(moveCol == "w" ? "0-1" : "1-0", "Repetition");
1433 else this.drawOffer = "threerep";
1434 }
1435 else if (this.drawOffer == "threerep") this.drawOffer = "";
1436 }
1437 if (!!this.game.mycolor && !data.receiveMyMove) {
1438 // NOTE: 'var' to see that variable outside this block
1439 var filtered_move = getFilteredMove(move);
1440 }
1441 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1442 // Notify turn on MyGames page:
1443 this.notifyMyGames(
1444 "turn",
1445 {
1446 gid: this.gameRef,
1447 turn: this.vr.turn
1448 }
1449 );
1450 }
1451 // Since corr games are stored at only one location, update should be
1452 // done only by one player for each move:
1453 if (
1454 this.game.type == "live" &&
1455 !!this.game.mycolor &&
1456 moveCol != this.game.mycolor &&
1457 this.game.moves.length >= 2
1458 ) {
1459 // Receive a move: update initime
1460 this.game.initime = Date.now();
1461 GameStorage.update(this.gameRef, {
1462 // It's my turn now!
1463 initime: this.game.initime
1464 });
1465 }
1466 if (
1467 !!this.game.mycolor &&
1468 !data.receiveMyMove &&
1469 (this.game.type == "live" || moveCol == this.game.mycolor)
1470 ) {
1471 let drawCode = "";
1472 switch (this.drawOffer) {
1473 case "threerep":
1474 drawCode = "t";
1475 break;
1476 case "sent":
1477 drawCode = this.game.mycolor;
1478 break;
1479 case "received":
1480 drawCode = V.GetOppCol(this.game.mycolor);
1481 break;
1482 }
1483 if (this.game.type == "corr") {
1484 // corr: only move, fen and score
1485 this.updateCorrGame({
1486 fen: this.game.fen,
1487 move: {
1488 squares: filtered_move,
1489 idx: origMovescount
1490 },
1491 // Code "n" for "None" to force reset (otherwise it's ignored)
1492 drawOffer: drawCode || "n"
1493 });
1494 }
1495 else {
1496 const updateStorage = () => {
1497 GameStorage.update(this.gameRef, {
1498 fen: this.game.fen,
1499 move: filtered_move,
1500 moveIdx: origMovescount,
1501 clocks: this.game.clocks,
1502 drawOffer: drawCode
1503 });
1504 };
1505 // The active tab can update storage immediately
1506 if (this.focus) updateStorage();
1507 // Small random delay otherwise
1508 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1509 }
1510 }
1511 // Send move ("newmove" event) to people in the room (if our turn)
1512 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1513 let sendMove = {
1514 move: filtered_move,
1515 index: origMovescount,
1516 // color is required to check if this is my move
1517 // (if several tabs opened)
1518 color: moveCol,
1519 cancelDrawOffer: this.drawOffer == ""
1520 };
1521 if (this.game.type == "live")
1522 sendMove["clock"] = this.game.clocks[colorIdx];
1523 // (Live) Clocks will re-start when the opponent pingback arrive
1524 this.opponentGotMove = false;
1525 this.send("newmove", {data: sendMove});
1526 // If the opponent doesn't reply gotmove soon enough, re-send move:
1527 // Do this at most 2 times, because more would mean network issues,
1528 // opponent would then be expected to disconnect/reconnect.
1529 let counter = 1;
1530 const currentUrl = document.location.href;
1531 this.retrySendmove = setInterval(
1532 () => {
1533 if (
1534 counter >= 3 ||
1535 this.opponentGotMove ||
1536 document.location.href != currentUrl //page change
1537 ) {
1538 clearInterval(this.retrySendmove);
1539 return;
1540 }
1541 const oppsid = this.getOppsid();
1542 if (!oppsid)
1543 // Opponent is disconnected: he'll ask last state
1544 clearInterval(this.retrySendmove);
1545 else {
1546 this.send("newmove", { data: sendMove, target: oppsid });
1547 counter++;
1548 }
1549 },
1550 1500
1551 );
1552 }
1553 else
1554 // Not my move or I'm an observer: just start other player's clock
1555 this.re_setClocks();
1556 };
1557 if (
1558 this.game.type == "corr" &&
1559 moveCol == this.game.mycolor &&
1560 !data.receiveMyMove
1561 ) {
1562 let boardDiv = document.querySelector(".game");
1563 const afterSetScore = () => {
1564 doProcessMove();
1565 if (this.st.settings.gotonext && this.nextIds.length > 0)
1566 this.showNextGame();
1567 else {
1568 // The board might have been hidden:
1569 if (boardDiv.style.visibility == "hidden")
1570 boardDiv.style.visibility = "visible";
1571 if (data.score == "*") this.re_setClocks();
1572 }
1573 };
1574 if (!V.CorrConfirm) {
1575 afterSetScore();
1576 return;
1577 }
1578 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1579 // We may play several moves in a row: in case of, remove listener:
1580 let elClone = el.cloneNode(true);
1581 el.parentNode.replaceChild(elClone, el);
1582 elClone.addEventListener(
1583 "click",
1584 () => {
1585 document.getElementById("modalConfirm").checked = false;
1586 if (!!data.score && data.score != "*")
1587 // Set score first
1588 this.gameOver(data.score, null, afterSetScore);
1589 else afterSetScore();
1590 }
1591 );
1592 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1593 const arMove = (Array.isArray(move) ? move : [move]);
1594 for (let i = 0; i < arMove.length; i++)
1595 V.PlayOnBoard(this.vr.board, arMove[i]);
1596 const position = this.vr.getBaseFen();
1597 for (let i = arMove.length - 1; i >= 0; i--)
1598 V.UndoOnBoard(this.vr.board, arMove[i]);
1599 if (["all","byrow"].includes(V.ShowMoves)) {
1600 this.curDiag = getDiagram({
1601 position: position,
1602 orientation: V.CanFlip ? this.game.mycolor : "w"
1603 });
1604 document.querySelector("#confirmDiv > .card").style.width =
1605 boardDiv.offsetWidth + "px";
1606 }
1607 else {
1608 // Incomplete information: just ask confirmation
1609 // Hide the board, because otherwise it could reveal infos
1610 boardDiv.style.visibility = "hidden";
1611 this.moveNotation = getFullNotation(move);
1612 }
1613 document.getElementById("modalConfirm").checked = true;
1614 }
1615 else {
1616 // Normal situation
1617 if (!!data.score && data.score != "*")
1618 this.gameOver(data.score, null, doProcessMove);
1619 else doProcessMove();
1620 }
1621 },
1622 cancelMove: function() {
1623 let boardDiv = document.querySelector(".game");
1624 if (boardDiv.style.visibility == "hidden")
1625 boardDiv.style.visibility = "visible";
1626 document.getElementById("modalConfirm").checked = false;
1627 this.$refs["basegame"].cancelLastMove();
1628 },
1629 // In corr games, callback to change page only after score is set:
1630 gameOver: function(score, scoreMsg, callback) {
1631 this.game.score = score;
1632 if (!scoreMsg) scoreMsg = getScoreMessage(score, V.ReverseColors);
1633 this.game.scoreMsg = scoreMsg;
1634 document.getElementById("modalRules").checked = false;
1635 // Display result in a un-missable way:
1636 document.getElementById("modalScore").checked = true;
1637 this.$set(this.game, "scoreMsg", scoreMsg);
1638 const myIdx = this.game.players.findIndex(p => {
1639 return (
1640 p.sid == this.st.user.sid ||
1641 (!!p.name && p.id == this.st.user.id)
1642 );
1643 });
1644 if (myIdx >= 0) {
1645 // OK, I play in this game
1646 const scoreObj = {
1647 score: score,
1648 scoreMsg: scoreMsg
1649 };
1650 if (this.game.type == "live") {
1651 GameStorage.update(this.gameRef, scoreObj);
1652 // Notify myself locally if I'm elsewhere:
1653 if (!this.focus) {
1654 notify(
1655 "Game over",
1656 { body: score + " : " + scoreMsg }
1657 );
1658 }
1659 if (!!callback) callback();
1660 }
1661 else this.updateCorrGame(scoreObj, callback);
1662 // Notify the score to main Hall.
1663 // TODO: only one player (currently double send)
1664 this.send("result", { gid: this.game.id, score: score });
1665 // Also to MyGames page (TODO: doubled as well...)
1666 this.notifyMyGames(
1667 "score",
1668 {
1669 gid: this.gameRef,
1670 score: score
1671 }
1672 );
1673 }
1674 else if (!!callback) callback();
1675 }
1676 }
1677 };
1678 </script>
1679
1680 <style lang="sass" scoped>
1681 #scoreDiv > .card, #rematchDiv > .card
1682 padding: 10px 0
1683 max-width: 430px
1684
1685 #rulesDiv > .card
1686 padding: 5px 0
1687 max-width: 50%
1688 max-height: 100%
1689 @media screen and (max-width: 1500px)
1690 max-width: 67%
1691 @media screen and (max-width: 1024px)
1692 max-width: 85%
1693 @media screen and (max-width: 767px)
1694 max-width: 100%
1695
1696 p.score-section
1697 margin: 0
1698 font-size: 1.3em
1699 span.score
1700 font-weight: bold
1701
1702 .connected
1703 background-color: lightgreen
1704
1705 #participants
1706 margin-left: 5px
1707
1708 .anonymous
1709 color: grey
1710 font-style: italic
1711
1712 #playersInfo > p
1713 margin: 0
1714
1715 @media screen and (max-width: 767px)
1716 .game
1717 width: 100%
1718
1719 #actions
1720 display: inline-block
1721 margin: 0
1722
1723 button
1724 display: inline-block
1725 margin: 0
1726 display: inline-flex
1727 img
1728 height: 22px
1729 display: flex
1730 @media screen and (max-width: 767px)
1731 height: 18px
1732
1733 #aboveBoard
1734 text-align: center
1735
1736 .user-bio
1737 display: inline
1738 font-size: 1.5rem
1739 @media screen and (max-width: 767px)
1740 font-size: 1.2rem
1741 padding: 0 3px
1742
1743 .variant-cadence
1744 padding-right: 10px
1745
1746 .variant-name
1747 font-weight: bold
1748 padding-right: 10px
1749
1750 span#nextGame
1751 background-color: #edda99
1752 cursor: pointer
1753 display: inline-block
1754 margin-right: 10px
1755
1756 span.separator
1757 display: inline-block
1758 margin: 0
1759 padding: 0
1760 width: 10px
1761
1762 span.time
1763 font-size: 2rem
1764 @media screen and (max-width: 767px)
1765 font-size: 1.5rem
1766 display: inline-block
1767 .time-left
1768 margin-left: 10px
1769 .time-right
1770 margin-left: 5px
1771 .time-separator
1772 margin-left: 5px
1773 position: relative
1774 top: -1px
1775
1776 span.yourturn
1777 color: #831B1B
1778 .time-separator
1779 animation: blink-animation 2s steps(3, start) infinite
1780 @keyframes blink-animation
1781 to
1782 visibility: hidden
1783
1784 .split-names
1785 display: inline-block
1786 margin: 0 15px
1787
1788 #chatWrap > .card
1789 padding-top: 20px
1790 max-width: 767px
1791 border: none
1792
1793 #confirmDiv > .card
1794 max-width: 767px
1795 max-height: 100%
1796
1797 .draw-sent, .draw-sent:hover
1798 background-color: lightyellow
1799
1800 .draw-received, .draw-received:hover
1801 background-color: #73C6B6
1802
1803 .draw-threerep, .draw-threerep:hover
1804 background-color: #D2B4DE
1805
1806 .rematch-sent, .rematch-sent:hover
1807 background-color: lightyellow
1808
1809 .rematch-received, .rematch-received:hover
1810 background-color: #48C9B0
1811
1812 .somethingnew
1813 background-color: #D2B4DE
1814
1815 .diagram
1816 margin: 0 auto
1817 width: 100%
1818
1819 #buttonsConfirm
1820 margin: 0
1821 & > button > span
1822 width: 100%
1823 text-align: center
1824
1825 button.acceptBtn
1826 background-color: lightgreen
1827 button.refuseBtn
1828 background-color: red
1829
1830 a#variantNameInGame
1831 color: var(--card-fore-color)
1832 text-align: center
1833 font-weight: bold
1834 font-size: calc(1rem * var(--heading-ratio))
1835 line-height: 1.2
1836 margin: calc(1.5 * var(--universal-margin))
1837 </style>
1838
1839 <style lang="sass">
1840 @import "@/styles/_rules.sass"
1841 @import "@/styles/_board_squares_img.sass"
1842 </style>