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