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