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