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