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