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