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