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