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