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