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