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