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