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