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