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