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