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