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