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