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