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