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