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