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