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