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