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