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