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