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