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