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