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