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