Fix Dynamo variant (hopefully...)
[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.toString().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 }
549 else {
550 // Complete my tmpIds:
551 Object.assign(this.people[sid].tmpIds, data.sockIds[sid]);
552 }
553 });
554 break;
555 case "connect":
556 if (!this.people[data.from[0]]) {
557 // focus depends on the tmpId (e.g. tab)
558 this.$set(
559 this.people,
560 data.from[0],
561 {
562 tmpIds: {
563 [data.from[1]]: { focus: true }
564 }
565 }
566 );
567 // For self multi-connects tests:
568 this.newConnect[data.from[0]] = true;
569 this.send("askidentity", { target: data.from[0] });
570 } else {
571 this.people[data.from[0]].tmpIds[data.from[1]] = { focus: true };
572 this.$forceUpdate(); //TODO: shouldn't be required
573 }
574 break;
575 case "disconnect":
576 if (!this.people[data.from[0]]) return;
577 delete this.people[data.from[0]].tmpIds[data.from[1]];
578 if (Object.keys(this.people[data.from[0]].tmpIds).length == 0)
579 this.$delete(this.people, data.from[0]);
580 else this.$forceUpdate(); //TODO: shouldn't be required
581 break;
582 case "getfocus": {
583 let player = this.people[data.from[0]];
584 if (!!player) {
585 player.tmpIds[data.from[1]].focus = true;
586 this.$forceUpdate(); //TODO: shouldn't be required
587 }
588 break;
589 }
590 case "losefocus": {
591 let player = this.people[data.from[0]];
592 if (!!player) {
593 player.tmpIds[data.from[1]].focus = false;
594 this.$forceUpdate(); //TODO: shouldn't be required
595 }
596 break;
597 }
598 case "askidentity": {
599 // Request for identification
600 const me = {
601 // Decompose to avoid revealing email
602 name: this.st.user.name,
603 sid: this.st.user.sid,
604 id: this.st.user.id
605 };
606 this.send("identity", { data: me, target: data.from });
607 break;
608 }
609 case "identity": {
610 const user = data.data;
611 let player = this.people[user.sid];
612 // player.tmpIds is already set
613 player.name = user.name;
614 player.id = user.id;
615 if (this.game.type == "live") {
616 const myGidx =
617 this.game.players.findIndex(p => p.sid == this.st.user.sid);
618 // Sometimes a player name isn't stored yet (TODO: why?)
619 if (
620 myGidx >= 0 &&
621 !this.game.players[1 - myGidx].name &&
622 this.game.players[1 - myGidx].sid == user.sid &&
623 !!user.name
624 ) {
625 this.game.players[1-myGidx].name = user.name;
626 GameStorage.update(
627 this.gameRef,
628 { playerName: { idx: 1 - myGidx, name: user.name } }
629 );
630 }
631 }
632 this.$forceUpdate(); //TODO: shouldn't be required
633 // If I multi-connect, kill current connexion if no mark (I'm older)
634 if (this.newConnect[user.sid]) {
635 delete this.newConnect[user.sid];
636 if (
637 user.id > 0 &&
638 user.id == this.st.user.id &&
639 user.sid != this.st.user.sid
640 ) {
641 this.cleanBeforeDestroy();
642 alert(this.st.tr["New connexion detected: tab now offline"]);
643 break;
644 }
645 }
646 // Ask potentially missed last state, if opponent and I play
647 if (
648 !this.gotLastate &&
649 !!this.game.mycolor &&
650 this.game.type == "live" &&
651 this.game.score == "*" &&
652 this.game.players.some(p => p.sid == user.sid)
653 ) {
654 this.send("asklastate", { target: user.sid });
655 let counter = 1;
656 this.askLastate = setInterval(
657 () => {
658 // Ask at most 3 times:
659 // if no reply after that there should be a network issue.
660 if (
661 counter < 3 &&
662 !this.gotLastate &&
663 !!this.people[user.sid]
664 ) {
665 this.send("asklastate", { target: user.sid });
666 counter++;
667 } else {
668 clearInterval(this.askLastate);
669 }
670 },
671 1500
672 );
673 }
674 break;
675 }
676 case "askgame":
677 // Send current (live or import) game,
678 // if not asked by any of the players
679 if (
680 this.game.type != "corr" &&
681 this.game.players.every(p => p.sid != data.from[0])
682 ) {
683 const myGame = {
684 id: this.game.id,
685 // FEN is current position, unused for now
686 fen: this.game.fen,
687 players: this.game.players,
688 vid: this.game.vid,
689 cadence: this.game.cadence,
690 score: this.game.score
691 };
692 this.send("game", { data: myGame, target: data.from });
693 }
694 break;
695 case "askfullgame":
696 const gameToSend = Object.keys(this.game)
697 .filter(k =>
698 [
699 "id","fen","players","vid","cadence","fenStart","vname",
700 "moves","clocks","score","drawOffer","rematchOffer"
701 ].includes(k))
702 .reduce(
703 (obj, k) => {
704 obj[k] = this.game[k];
705 return obj;
706 },
707 {}
708 );
709 this.send("fullgame", { data: gameToSend, target: data.from });
710 break;
711 case "fullgame":
712 if (!!data.data.empty) {
713 alert(this.st.tr["The game should be in another tab"]);
714 this.$router.go(-1);
715 }
716 else
717 // Callback "roomInit" to poll clients only after game is loaded
718 this.loadVariantThenGame(data.data, this.roomInit);
719 break;
720 case "asklastate":
721 // Sending informative last state if I played a move or score != "*"
722 // If the game or moves aren't loaded yet, delay the sending:
723 // TODO: socket init after game load, so the game is supposedly ready
724 if (!this.game || !this.game.moves) this.lastateAsked = true;
725 else this.sendLastate(data.from);
726 break;
727 case "lastate": {
728 // Got opponent infos about last move
729 this.gotLastate = true;
730 this.lastate = data.data;
731 if (this.game.rendered)
732 // Game is rendered (Board component)
733 this.processLastate();
734 // Else: will be processed when game is ready
735 break;
736 }
737 case "newmove": {
738 const movePlus = data.data;
739 const movesCount = this.game.moves.length;
740 if (movePlus.index > movesCount) {
741 // This can only happen if I'm an observer and missed a move.
742 if (this.gotMoveIdx < movePlus.index)
743 this.gotMoveIdx = movePlus.index;
744 if (!this.gameIsLoading) this.askGameAgain();
745 }
746 else {
747 if (
748 movePlus.index < movesCount ||
749 this.gotMoveIdx >= movePlus.index
750 ) {
751 // Opponent re-send but we already have the move:
752 // (maybe he didn't receive our pingback...)
753 this.send("gotmove", {data: movePlus.index, target: data.from});
754 } else {
755 this.gotMoveIdx = movePlus.index;
756 const receiveMyMove = (movePlus.color == this.game.mycolor);
757 const moveColIdx = ["w", "b"].indexOf(movePlus.color);
758 if (!receiveMyMove && !!this.game.mycolor) {
759 // Notify opponent that I got the move:
760 this.send(
761 "gotmove",
762 { data: movePlus.index, target: data.from }
763 );
764 // And myself if I'm elsewhere:
765 if (!this.focus) {
766 notify(
767 "New move",
768 {
769 body:
770 (this.game.players[moveColIdx].name || "@nonymous") +
771 " just played."
772 }
773 );
774 }
775 }
776 if (movePlus.cancelDrawOffer) {
777 // Opponent refuses draw
778 this.drawOffer = "";
779 // NOTE for corr games: drawOffer reset by player in turn
780 if (
781 this.game.type == "live" &&
782 !!this.game.mycolor &&
783 !receiveMyMove
784 ) {
785 GameStorage.update(this.gameRef, { drawOffer: "" });
786 }
787 }
788 this.$refs["basegame"].play(
789 movePlus.move, "received", null, true);
790 this.game.clocks[moveColIdx] = movePlus.clock;
791 this.processMove(
792 movePlus.move,
793 { receiveMyMove: receiveMyMove }
794 );
795 }
796 }
797 break;
798 }
799 case "gotmove": {
800 this.opponentGotMove = true;
801 // Now his clock starts running on my side:
802 const oppIdx = ['w','b'].indexOf(this.vr.turn);
803 // NOTE: next line to avoid multi-resetClocks when several tabs
804 // on same game, resulting in a faster countdown.
805 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
806 this.re_setClocks();
807 break;
808 }
809 case "resign":
810 const score = (data.data == "b" ? "1-0" : "0-1");
811 const side = (data.data == "w" ? "White" : "Black");
812 this.gameOver(score, side + " surrender");
813 break;
814 case "abort":
815 this.gameOver("?", "Stop");
816 break;
817 case "draw":
818 this.gameOver("1/2", data.data);
819 break;
820 case "drawoffer":
821 // NOTE: observers don't know who offered draw
822 this.drawOffer = "received";
823 if (!!this.game.mycolor && this.game.type == "live") {
824 GameStorage.update(
825 this.gameRef,
826 { drawOffer: V.GetOppCol(this.game.mycolor) }
827 );
828 }
829 break;
830 case "rematchoffer":
831 // NOTE: observers don't know who offered rematch
832 this.rematchOffer = data.data ? "received" : "";
833 if (!!this.game.mycolor && this.game.type == "live") {
834 GameStorage.update(
835 this.gameRef,
836 { rematchOffer: V.GetOppCol(this.game.mycolor) }
837 );
838 }
839 break;
840 case "newgame": {
841 // A game started, redirect if I'm playing in
842 const gameInfo = data.data;
843 const gameType = this.getGameType(gameInfo);
844 if (
845 gameType == "live" &&
846 gameInfo.players.some(p => p.sid == this.st.user.sid)
847 ) {
848 this.addAndGotoLiveGame(gameInfo);
849 } else if (
850 gameType == "corr" &&
851 gameInfo.players.some(p => p.id == this.st.user.id)
852 ) {
853 this.$router.push("/game/" + gameInfo.id);
854 } else {
855 this.rematchId = gameInfo.id;
856 document.getElementById("modalInfo").checked = true;
857 }
858 break;
859 }
860 case "newchat": {
861 let chat = data.data;
862 this.$refs["chatcomp"].newChat(chat);
863 if (this.game.type == "live") {
864 chat.added = Date.now();
865 if (!!this.game.mycolor)
866 GameStorage.update(this.gameRef, { chat: chat });
867 }
868 if (!document.getElementById("modalChat").checked)
869 document.getElementById("chatBtn").classList.add("somethingnew");
870 break;
871 }
872 }
873 },
874 updateCorrGame: function(obj, callback) {
875 ajax(
876 "/games",
877 "PUT",
878 {
879 data: {
880 gid: this.gameRef,
881 newObj: obj
882 },
883 success: () => {
884 if (!!callback) callback();
885 }
886 }
887 );
888 },
889 sendLastate: function(target) {
890 // Send our "last state" informations to opponent
891 const L = this.game.moves.length;
892 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
893 const myLastate = {
894 lastMove:
895 (L > 0 && this.vr.turn != this.game.mycolor)
896 ? this.game.moves[L - 1]
897 : undefined,
898 clock: this.game.clocks[myIdx],
899 // Since we played a move (or abort or resign),
900 // only drawOffer=="sent" is possible
901 drawSent: this.drawOffer == "sent",
902 rematchSent: this.rematchOffer == "sent",
903 score: this.game.score != "*" ? this.game.score : undefined,
904 scoreMsg: this.game.score != "*" ? this.game.scoreMsg : undefined,
905 movesCount: L
906 };
907 this.send("lastate", { data: myLastate, target: target });
908 },
909 // lastate was received, but maybe game wasn't ready yet:
910 processLastate: function() {
911 const data = this.lastate;
912 this.lastate = undefined; //security...
913 const L = this.game.moves.length;
914 const oppIdx = 1 - ["w", "b"].indexOf(this.game.mycolor);
915 this.game.clocks[oppIdx] = data.clock;
916 if (data.movesCount > L) {
917 // Just got last move from him
918 this.$refs["basegame"].play(data.lastMove, "received", null, true);
919 this.processMove(data.lastMove);
920 } else {
921 if (!!this.clockUpdate) clearInterval(this.clockUpdate);
922 this.re_setClocks();
923 }
924 if (data.drawSent) this.drawOffer = "received";
925 if (data.rematchSent) this.rematchOffer = "received";
926 if (!!data.score) {
927 this.drawOffer = "";
928 if (this.game.score == "*")
929 this.gameOver(data.score, data.scoreMsg);
930 }
931 },
932 clickDraw: function() {
933 if (!this.game.mycolor || this.game.type == "import") return;
934 if (["received", "threerep"].includes(this.drawOffer)) {
935 if (!confirm(this.st.tr["Accept draw?"])) return;
936 const message =
937 this.drawOffer == "received"
938 ? "Mutual agreement"
939 : "Three repetitions";
940 this.send("draw", { data: message });
941 this.gameOver("1/2", message);
942 } else if (this.drawOffer == "") {
943 // No effect if drawOffer == "sent"
944 if (this.game.mycolor != this.vr.turn) {
945 alert(this.st.tr["Draw offer only in your turn"]);
946 return;
947 }
948 if (!confirm(this.st.tr["Offer draw?"])) return;
949 this.drawOffer = "sent";
950 this.send("drawoffer");
951 if (this.game.type == "live") {
952 GameStorage.update(
953 this.gameRef,
954 { drawOffer: this.game.mycolor }
955 );
956 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
957 }
958 },
959 addAndGotoLiveGame: function(gameInfo, callback) {
960 const game = Object.assign(
961 {},
962 gameInfo,
963 {
964 // (other) Game infos: constant
965 fenStart: gameInfo.fen,
966 vname: this.game.vname,
967 created: Date.now(),
968 // Game state (including FEN): will be updated
969 moves: [],
970 clocks: [-1, -1], //-1 = unstarted
971 score: "*"
972 }
973 );
974 GameStorage.add(game, (err) => {
975 // No error expected.
976 if (!err) {
977 if (this.st.settings.sound)
978 new Audio("/sounds/newgame.flac").play().catch(() => {});
979 if (!!callback) callback();
980 this.$router.push("/game/" + gameInfo.id);
981 }
982 });
983 },
984 clickRematch: function() {
985 if (!this.game.mycolor || this.game.type == "import") return;
986 if (this.rematchOffer == "received") {
987 // Start a new game!
988 let gameInfo = {
989 id: getRandString(), //ignored if corr
990 fen: V.GenRandInitFen(this.game.randomness),
991 players: this.game.players.reverse(),
992 vid: this.game.vid,
993 cadence: this.game.cadence
994 };
995 const notifyNewGame = () => {
996 const oppsid = this.getOppsid(); //may be null
997 this.send("rnewgame", { data: gameInfo, oppsid: oppsid });
998 // To main Hall if corr game:
999 if (this.game.type == "corr")
1000 this.send("newgame", { data: gameInfo, page: "/" });
1001 // Also to MyGames page:
1002 this.notifyMyGames("newgame", gameInfo);
1003 };
1004 if (this.game.type == "live")
1005 this.addAndGotoLiveGame(gameInfo, notifyNewGame);
1006 else {
1007 // corr game
1008 ajax(
1009 "/games",
1010 "POST",
1011 {
1012 // cid is useful to delete the challenge:
1013 data: { gameInfo: gameInfo },
1014 success: (response) => {
1015 gameInfo.id = response.gameId;
1016 notifyNewGame();
1017 this.$router.push("/game/" + response.gameId);
1018 }
1019 }
1020 );
1021 }
1022 } else if (this.rematchOffer == "") {
1023 this.rematchOffer = "sent";
1024 this.send("rematchoffer", { data: true });
1025 if (this.game.type == "live") {
1026 GameStorage.update(
1027 this.gameRef,
1028 { rematchOffer: this.game.mycolor }
1029 );
1030 } else this.updateCorrGame({ rematchOffer: this.game.mycolor });
1031 } else if (this.rematchOffer == "sent") {
1032 // Toggle rematch offer (on --> off)
1033 this.rematchOffer = "";
1034 this.send("rematchoffer", { data: false });
1035 if (this.game.type == "live") {
1036 GameStorage.update(
1037 this.gameRef,
1038 { rematchOffer: '' }
1039 );
1040 } else this.updateCorrGame({ rematchOffer: 'n' });
1041 }
1042 },
1043 abortGame: function() {
1044 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
1045 return;
1046 this.gameOver("?", "Stop");
1047 this.send("abort");
1048 },
1049 resign: function() {
1050 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
1051 return;
1052 this.send("resign", { data: this.game.mycolor });
1053 const score = (this.game.mycolor == "w" ? "0-1" : "1-0");
1054 const side = (this.game.mycolor == "w" ? "White" : "Black");
1055 this.gameOver(score, side + " surrender");
1056 },
1057 loadGame: function(game, callback) {
1058 const gtype = game.type || this.getGameType(game);
1059 const tc = extractTime(game.cadence);
1060 const myIdx = game.players.findIndex(p => {
1061 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1062 });
1063 // Sometimes the name isn't stored yet (TODO: why?)
1064 if (
1065 myIdx >= 0 &&
1066 gtype == "live" &&
1067 !game.players[myIdx].name &&
1068 !!this.st.user.name
1069 ) {
1070 game.players[myIdx].name = this.st.user.name;
1071 GameStorage.update(
1072 game.id,
1073 { playerName: { idx: myIdx, name: this.st.user.name } }
1074 );
1075 }
1076 // "mycolor" is undefined for observers
1077 const mycolor = [undefined, "w", "b"][myIdx + 1];
1078 if (gtype == "corr") {
1079 if (mycolor == 'w') game.chatRead = game.chatReadWhite;
1080 else if (mycolor == 'b') game.chatRead = game.chatReadBlack;
1081 // NOTE: clocks in seconds
1082 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
1083 game.clocks = [tc.mainTime, tc.mainTime];
1084 const L = game.moves.length;
1085 if (game.score == "*") {
1086 // Adjust clocks
1087 if (L >= 2) {
1088 game.clocks[L % 2] -=
1089 (Date.now() - game.moves[L-1].played) / 1000;
1090 }
1091 }
1092 // Now that we used idx and played, re-format moves as for live games
1093 game.moves = game.moves.map(m => m.squares);
1094 }
1095 else if (gtype == "live") {
1096 if (game.clocks[0] < 0) {
1097 // Game is unstarted. clock is ignored until move 2
1098 game.clocks = [tc.mainTime, tc.mainTime];
1099 if (myIdx >= 0) {
1100 // I play in this live game
1101 GameStorage.update(
1102 game.id,
1103 { clocks: game.clocks }
1104 );
1105 }
1106 } else {
1107 if (!!game.initime)
1108 // It's my turn: clocks not updated yet
1109 game.clocks[myIdx] -= (Date.now() - game.initime) / 1000;
1110 }
1111 }
1112 else
1113 // gtype == "import"
1114 game.clocks = [tc.mainTime, tc.mainTime];
1115 // Live games before 26/03/2020 don't have chat history:
1116 if (!game.chats) game.chats = []; //TODO: remove line
1117 // Sort chat messages from newest to oldest
1118 game.chats.sort((c1, c2) => c2.added - c1.added);
1119 if (
1120 myIdx >= 0 &&
1121 game.chats.length > 0 &&
1122 (!game.chatRead || game.chatRead < game.chats[0].added)
1123 ) {
1124 // A chat message arrived since my last reading:
1125 document.getElementById("chatBtn").classList.add("somethingnew");
1126 }
1127 // TODO: merge next 2 "if" conditions
1128 if (!!game.drawOffer) {
1129 if (game.drawOffer == "t")
1130 // Three repetitions
1131 this.drawOffer = "threerep";
1132 else {
1133 // Draw offered by any of the players:
1134 if (myIdx < 0) this.drawOffer = "received";
1135 else {
1136 // I play in this game:
1137 if (
1138 (game.drawOffer == "w" && myIdx == 0) ||
1139 (game.drawOffer == "b" && myIdx == 1)
1140 )
1141 this.drawOffer = "sent";
1142 else this.drawOffer = "received";
1143 }
1144 }
1145 }
1146 if (!!game.rematchOffer) {
1147 if (myIdx < 0) this.rematchOffer = "received";
1148 else {
1149 // I play in this game:
1150 if (
1151 (game.rematchOffer == "w" && myIdx == 0) ||
1152 (game.rematchOffer == "b" && myIdx == 1)
1153 )
1154 this.rematchOffer = "sent";
1155 else this.rematchOffer = "received";
1156 }
1157 }
1158 this.repeat = {}; //reset: scan past moves' FEN:
1159 let repIdx = 0;
1160 this.vr = new V(game.fenStart);
1161 let curTurn = "n";
1162 game.moves.forEach(m => {
1163 playMove(m, this.vr);
1164 const fenIdx = this.vr.getFenForRepeat();
1165 this.repeat[fenIdx] = this.repeat[fenIdx]
1166 ? this.repeat[fenIdx] + 1
1167 : 1;
1168 });
1169 // Imported games don't have current FEN
1170 if (!game.fen) game.fen = this.vr.getFen();
1171 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
1172 this.game = Object.assign(
1173 // NOTE: assign mycolor here, since BaseGame could also be VS computer
1174 {
1175 type: gtype,
1176 increment: tc.increment,
1177 mycolor: mycolor,
1178 // opponent sid not strictly required (or available), but easier
1179 // at least oppsid or oppid is available anyway:
1180 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
1181 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id
1182 },
1183 game
1184 );
1185 this.$refs["basegame"].re_setVariables(this.game);
1186 if (!this.gameIsLoading) {
1187 // Initial loading:
1188 this.gotMoveIdx = game.moves.length - 1;
1189 // If we arrive here after 'nextGame' action, the board might be hidden
1190 let boardDiv = document.querySelector(".game");
1191 if (!!boardDiv && boardDiv.style.visibility == "hidden")
1192 boardDiv.style.visibility = "visible";
1193 }
1194 this.re_setClocks();
1195 this.$nextTick(() => {
1196 this.game.rendered = true;
1197 // Did lastate arrive before game was rendered?
1198 if (this.lastate) this.processLastate();
1199 });
1200 if (this.lastateAsked) {
1201 this.lastateAsked = false;
1202 this.sendLastate(game.oppsid);
1203 }
1204 if (this.gameIsLoading) {
1205 this.gameIsLoading = false;
1206 if (this.gotMoveIdx >= game.moves.length)
1207 // Some moves arrived meanwhile...
1208 this.askGameAgain();
1209 }
1210 if (!!callback) callback();
1211 },
1212 loadVariantThenGame: async function(game, callback) {
1213 await import("@/variants/" + game.vname + ".js")
1214 .then((vModule) => {
1215 window.V = vModule[game.vname + "Rules"];
1216 this.loadGame(game, callback);
1217 });
1218 },
1219 // 3 cases for loading a game:
1220 // - from indexedDB (running or completed live game I play)
1221 // - from server (one correspondance game I play[ed] or not)
1222 // - from remote peer (one live game I don't play, finished or not)
1223 fetchGame: function(callback) {
1224 if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) {
1225 // corr games identifiers are integers
1226 ajax(
1227 "/games",
1228 "GET",
1229 {
1230 data: { gid: this.gameRef },
1231 success: (res) => {
1232 res.game.moves.forEach(m => {
1233 m.squares = JSON.parse(m.squares);
1234 });
1235 callback(res.game);
1236 }
1237 }
1238 );
1239 }
1240 else if (!!this.gameRef.match(/^i/))
1241 // Game import (maybe remote)
1242 ImportgameStorage.get(this.gameRef, callback);
1243 else
1244 // Local live game (or remote)
1245 GameStorage.get(this.gameRef, callback);
1246 },
1247 re_setClocks: function() {
1248 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
1249 if (this.game.moves.length < 2 || this.game.score != "*") {
1250 // 1st move not completed yet, or game over: freeze time
1251 return;
1252 }
1253 const currentTurn = this.vr.turn;
1254 const currentMovesCount = this.game.moves.length;
1255 const colorIdx = ["w", "b"].indexOf(currentTurn);
1256 this.clockUpdate = setInterval(
1257 () => {
1258 if (
1259 this.game.clocks[colorIdx] < 0 ||
1260 this.game.moves.length > currentMovesCount ||
1261 this.game.score != "*"
1262 ) {
1263 clearInterval(this.clockUpdate);
1264 this.clockUpdate = null;
1265 if (this.game.clocks[colorIdx] < 0)
1266 this.gameOver(
1267 currentTurn == "w" ? "0-1" : "1-0",
1268 "Time"
1269 );
1270 } else {
1271 this.$set(
1272 this.virtualClocks,
1273 colorIdx,
1274 ppt(Math.max(0, --this.game.clocks[colorIdx])).split(':')
1275 );
1276 }
1277 },
1278 1000
1279 );
1280 },
1281 // Update variables and storage after a move:
1282 processMove: function(move, data) {
1283 if (this.game.type == "import")
1284 // Shouldn't receive any messages in this mode:
1285 return;
1286 if (!data) data = {};
1287 const moveCol = this.vr.turn;
1288 const colorIdx = ["w", "b"].indexOf(moveCol);
1289 const nextIdx = 1 - colorIdx;
1290 const doProcessMove = () => {
1291 const origMovescount = this.game.moves.length;
1292 // The move is (about to be) played: stop clock
1293 clearInterval(this.clockUpdate);
1294 this.clockUpdate = null;
1295 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1296 if (this.drawOffer == "received")
1297 // I refuse draw
1298 this.drawOffer = "";
1299 if (this.game.type == "live" && origMovescount >= 2) {
1300 this.game.clocks[colorIdx] += this.game.increment;
1301 // For a correct display in casqe of disconnected opponent:
1302 this.$set(
1303 this.virtualClocks,
1304 colorIdx,
1305 ppt(this.game.clocks[colorIdx]).split(':')
1306 );
1307 GameStorage.update(this.gameRef, {
1308 // It's not my turn anymore:
1309 initime: null
1310 });
1311 }
1312 }
1313 // Update current game object:
1314 playMove(move, this.vr);
1315 if (!data.score)
1316 // Received move, score is computed in BaseGame, but maybe not yet.
1317 // ==> Compute it here, although this is redundant (TODO)
1318 data.score = this.vr.getCurrentScore();
1319 if (data.score != "*") this.gameOver(data.score);
1320 this.game.moves.push(move);
1321 this.game.fen = this.vr.getFen();
1322 if (this.game.type == "corr") {
1323 // In corr games, just reset clock to mainTime:
1324 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
1325 }
1326 // If repetition detected, consider that a draw offer was received:
1327 const fenObj = this.vr.getFenForRepeat();
1328 this.repeat[fenObj] =
1329 !!this.repeat[fenObj]
1330 ? this.repeat[fenObj] + 1
1331 : 1;
1332 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
1333 else if (this.drawOffer == "threerep") this.drawOffer = "";
1334 if (!!this.game.mycolor && !data.receiveMyMove) {
1335 // NOTE: 'var' to see that variable outside this block
1336 var filtered_move = getFilteredMove(move);
1337 }
1338 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1339 // Notify turn on MyGames page:
1340 this.notifyMyGames(
1341 "turn",
1342 {
1343 gid: this.gameRef,
1344 turn: this.vr.turn
1345 }
1346 );
1347 }
1348 // Since corr games are stored at only one location, update should be
1349 // done only by one player for each move:
1350 if (
1351 this.game.type == "live" &&
1352 !!this.game.mycolor &&
1353 moveCol != this.game.mycolor &&
1354 this.game.moves.length >= 2
1355 ) {
1356 // Receive a move: update initime
1357 this.game.initime = Date.now();
1358 GameStorage.update(this.gameRef, {
1359 // It's my turn now!
1360 initime: this.game.initime
1361 });
1362 }
1363 if (
1364 !!this.game.mycolor &&
1365 !data.receiveMyMove &&
1366 (this.game.type == "live" || moveCol == this.game.mycolor)
1367 ) {
1368 let drawCode = "";
1369 switch (this.drawOffer) {
1370 case "threerep":
1371 drawCode = "t";
1372 break;
1373 case "sent":
1374 drawCode = this.game.mycolor;
1375 break;
1376 case "received":
1377 drawCode = V.GetOppCol(this.game.mycolor);
1378 break;
1379 }
1380 if (this.game.type == "corr") {
1381 // corr: only move, fen and score
1382 this.updateCorrGame({
1383 fen: this.game.fen,
1384 move: {
1385 squares: filtered_move,
1386 idx: origMovescount
1387 },
1388 // Code "n" for "None" to force reset (otherwise it's ignored)
1389 drawOffer: drawCode || "n"
1390 });
1391 }
1392 else {
1393 const updateStorage = () => {
1394 GameStorage.update(this.gameRef, {
1395 fen: this.game.fen,
1396 move: filtered_move,
1397 moveIdx: origMovescount,
1398 clocks: this.game.clocks,
1399 drawOffer: drawCode
1400 });
1401 };
1402 // The active tab can update storage immediately
1403 if (this.focus) updateStorage();
1404 // Small random delay otherwise
1405 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1406 }
1407 }
1408 // Send move ("newmove" event) to people in the room (if our turn)
1409 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1410 let sendMove = {
1411 move: filtered_move,
1412 index: origMovescount,
1413 // color is required to check if this is my move
1414 // (if several tabs opened)
1415 color: moveCol,
1416 cancelDrawOffer: this.drawOffer == ""
1417 };
1418 if (this.game.type == "live")
1419 sendMove["clock"] = this.game.clocks[colorIdx];
1420 // (Live) Clocks will re-start when the opponent pingback arrive
1421 this.opponentGotMove = false;
1422 this.send("newmove", {data: sendMove});
1423 // If the opponent doesn't reply gotmove soon enough, re-send move:
1424 // Do this at most 2 times, because mpore would mean network issues,
1425 // opponent would then be expected to disconnect/reconnect.
1426 let counter = 1;
1427 const currentUrl = document.location.href;
1428 this.retrySendmove = setInterval(
1429 () => {
1430 if (
1431 counter >= 3 ||
1432 this.opponentGotMove ||
1433 document.location.href != currentUrl //page change
1434 ) {
1435 clearInterval(this.retrySendmove);
1436 return;
1437 }
1438 const oppsid = this.getOppsid();
1439 if (!oppsid)
1440 // Opponent is disconnected: he'll ask last state
1441 clearInterval(this.retrySendmove);
1442 else {
1443 this.send("newmove", { data: sendMove, target: oppsid });
1444 counter++;
1445 }
1446 },
1447 1500
1448 );
1449 }
1450 else
1451 // Not my move or I'm an observer: just start other player's clock
1452 this.re_setClocks();
1453 };
1454 if (
1455 this.game.type == "corr" &&
1456 moveCol == this.game.mycolor &&
1457 !data.receiveMyMove
1458 ) {
1459 let boardDiv = document.querySelector(".game");
1460 const afterSetScore = () => {
1461 doProcessMove();
1462 if (this.st.settings.gotonext && this.nextIds.length > 0)
1463 this.showNextGame();
1464 else {
1465 // The board might have been hidden:
1466 if (boardDiv.style.visibility == "hidden")
1467 boardDiv.style.visibility = "visible";
1468 if (data.score == "*") this.re_setClocks();
1469 }
1470 };
1471 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1472 // We may play several moves in a row: in case of, remove listener:
1473 let elClone = el.cloneNode(true);
1474 el.parentNode.replaceChild(elClone, el);
1475 elClone.addEventListener(
1476 "click",
1477 () => {
1478 document.getElementById("modalConfirm").checked = false;
1479 if (!!data.score && data.score != "*")
1480 // Set score first
1481 this.gameOver(data.score, null, afterSetScore);
1482 else afterSetScore();
1483 }
1484 );
1485 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1486 const arMove = (Array.isArray(move) ? move : [move]);
1487 for (let i = 0; i < arMove.length; i++)
1488 V.PlayOnBoard(this.vr.board, arMove[i]);
1489 const position = this.vr.getBaseFen();
1490 for (let i = arMove.length - 1; i >= 0; i--)
1491 V.UndoOnBoard(this.vr.board, arMove[i]);
1492 if (["all","byrow"].includes(V.ShowMoves)) {
1493 this.curDiag = getDiagram({
1494 position: position,
1495 orientation: V.CanFlip ? this.game.mycolor : "w"
1496 });
1497 document.querySelector("#confirmDiv > .card").style.width =
1498 boardDiv.offsetWidth + "px";
1499 } else {
1500 // Incomplete information: just ask confirmation
1501 // Hide the board, because otherwise it could reveal infos
1502 boardDiv.style.visibility = "hidden";
1503 this.moveNotation = getFullNotation(move);
1504 }
1505 document.getElementById("modalConfirm").checked = true;
1506 }
1507 else {
1508 // Normal situation
1509 if (!!data.score && data.score != "*")
1510 this.gameOver(data.score, null, doProcessMove);
1511 else doProcessMove();
1512 }
1513 },
1514 cancelMove: function() {
1515 let boardDiv = document.querySelector(".game");
1516 if (boardDiv.style.visibility == "hidden")
1517 boardDiv.style.visibility = "visible";
1518 document.getElementById("modalConfirm").checked = false;
1519 this.$refs["basegame"].cancelLastMove();
1520 },
1521 // In corr games, callback to change page only after score is set:
1522 gameOver: function(score, scoreMsg, callback) {
1523 this.game.score = score;
1524 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1525 this.game.scoreMsg = scoreMsg;
1526 this.$set(this.game, "scoreMsg", scoreMsg);
1527 const myIdx = this.game.players.findIndex(p => {
1528 return p.sid == this.st.user.sid || p.id == this.st.user.id;
1529 });
1530 if (myIdx >= 0) {
1531 // OK, I play in this game
1532 const scoreObj = {
1533 score: score,
1534 scoreMsg: scoreMsg
1535 };
1536 if (this.game.type == "live") {
1537 GameStorage.update(this.gameRef, scoreObj);
1538 // Notify myself locally if I'm elsewhere:
1539 if (!this.focus) {
1540 notify(
1541 "Game over",
1542 { body: score + " : " + scoreMsg }
1543 );
1544 }
1545 if (!!callback) callback();
1546 }
1547 else this.updateCorrGame(scoreObj, callback);
1548 // Notify the score to main Hall.
1549 // TODO: only one player (currently double send)
1550 this.send("result", { gid: this.game.id, score: score });
1551 // Also to MyGames page (TODO: doubled as well...)
1552 this.notifyMyGames(
1553 "score",
1554 {
1555 gid: this.gameRef,
1556 score: score
1557 }
1558 );
1559 }
1560 else if (!!callback) callback();
1561 }
1562 }
1563 };
1564 </script>
1565
1566 <style lang="sass" scoped>
1567 #infoDiv > .card
1568 padding: 15px 0
1569 max-width: 430px
1570
1571 .connected
1572 background-color: lightgreen
1573
1574 #participants
1575 margin-left: 5px
1576
1577 .anonymous
1578 color: grey
1579 font-style: italic
1580
1581 #playersInfo > p
1582 margin: 0
1583
1584 @media screen and (min-width: 768px)
1585 #actions
1586 width: 300px
1587 @media screen and (max-width: 767px)
1588 .game
1589 width: 100%
1590
1591 #actions
1592 display: inline-block
1593 margin: 0
1594
1595 button
1596 display: inline-block
1597 margin: 0
1598 display: inline-flex
1599 img
1600 height: 22px
1601 display: flex
1602 @media screen and (max-width: 767px)
1603 height: 18px
1604
1605 @media screen and (max-width: 767px)
1606 #aboveBoard
1607 text-align: center
1608 @media screen and (min-width: 768px)
1609 #aboveBoard
1610 margin-left: 30%
1611
1612 .variant-cadence
1613 padding-right: 10px
1614
1615 .variant-name
1616 font-weight: bold
1617 padding-right: 10px
1618
1619 span#nextGame
1620 background-color: #edda99
1621 cursor: pointer
1622 display: inline-block
1623 margin-right: 10px
1624
1625 span.name
1626 font-size: 1.5rem
1627 padding: 0 3px
1628
1629 span.time
1630 font-size: 2rem
1631 display: inline-block
1632 .time-left
1633 margin-left: 10px
1634 .time-right
1635 margin-left: 5px
1636 .time-separator
1637 margin-left: 5px
1638 position: relative
1639 top: -1px
1640
1641 span.yourturn
1642 color: #831B1B
1643 .time-separator
1644 animation: blink-animation 2s steps(3, start) infinite
1645 @keyframes blink-animation
1646 to
1647 visibility: hidden
1648
1649 .split-names
1650 display: inline-block
1651 margin: 0 15px
1652
1653 #chatWrap > .card
1654 padding-top: 20px
1655 max-width: 767px
1656 border: none
1657
1658 #confirmDiv > .card
1659 max-width: 767px
1660 max-height: 100%
1661
1662 .draw-sent, .draw-sent:hover
1663 background-color: lightyellow
1664
1665 .draw-received, .draw-received:hover
1666 background-color: lightgreen
1667
1668 .draw-threerep, .draw-threerep:hover
1669 background-color: #e4d1fc
1670
1671 .rematch-sent, .rematch-sent:hover
1672 background-color: lightyellow
1673
1674 .rematch-received, .rematch-received:hover
1675 background-color: lightgreen
1676
1677 .somethingnew
1678 background-color: #c5fefe
1679
1680 .diagram
1681 margin: 0 auto
1682 width: 100%
1683
1684 #buttonsConfirm
1685 margin: 0
1686 & > button > span
1687 width: 100%
1688 text-align: center
1689
1690 button.acceptBtn
1691 background-color: lightgreen
1692 button.refuseBtn
1693 background-color: red
1694 </style>