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