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