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