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