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