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