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