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