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