Fixes for corr games update + incomplete info (do not show board)
[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 const currentTurn = this.vr.turn;
899 const currentMovesCount = this.game.moves.length;
900 const colorIdx = ["w", "b"].indexOf(currentTurn);
901 let countdown =
902 this.game.clocks[colorIdx] -
903 (Date.now() - this.game.initime[colorIdx]) / 1000;
904 this.virtualClocks = [0, 1].map(i => {
905 const removeTime =
906 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
907 return ppt(this.game.clocks[i] - removeTime).split(':');
908 });
909 this.clockUpdate = setInterval(() => {
910 if (
911 countdown < 0 ||
912 this.game.moves.length > currentMovesCount ||
913 this.game.score != "*"
914 ) {
915 clearInterval(this.clockUpdate);
916 if (countdown < 0)
917 this.gameOver(
918 currentTurn == "w" ? "0-1" : "1-0",
919 "Time"
920 );
921 } else
922 this.$set(
923 this.virtualClocks,
924 colorIdx,
925 ppt(Math.max(0, --countdown)).split(':')
926 );
927 }, 1000);
928 },
929 // Update variables and storage after a move:
930 processMove: function(move, data) {
931 if (!data) data = {};
932 const moveCol = this.vr.turn;
933 const doProcessMove = () => {
934 const colorIdx = ["w", "b"].indexOf(moveCol);
935 const nextIdx = 1 - colorIdx;
936 const origMovescount = this.game.moves.length;
937 let addTime =
938 this.game.type == "live"
939 ? (data.addTime || 0)
940 : undefined;
941 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
942 if (this.drawOffer == "received")
943 // I refuse draw
944 this.drawOffer = "";
945 if (this.game.type == "live" && origMovescount >= 2) {
946 const elapsed = Date.now() - this.game.initime[colorIdx];
947 // elapsed time is measured in milliseconds
948 addTime = this.game.increment - elapsed / 1000;
949 }
950 }
951 // Update current game object:
952 playMove(move, this.vr);
953 if (!data.score) {
954 // Received move, score has not been computed in BaseGame (!!noemit)
955 const score = this.vr.getCurrentScore();
956 if (score != "*") this.gameOver(score);
957 }
958 // TODO: notifyTurn: "changeturn" message
959 this.game.moves.push(move);
960 // (add)Time indication: useful in case of lastate infos requested
961 if (this.game.type == "live")
962 this.game.addTimes.push(addTime);
963 this.game.fen = this.vr.getFen();
964 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
965 // In corr games, just reset clock to mainTime:
966 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
967 // data.initime is set only when I receive a "lastate" move from opponent
968 this.game.initime[nextIdx] = data.initime || Date.now();
969 // If repetition detected, consider that a draw offer was received:
970 const fenObj = this.vr.getFenForRepeat();
971 this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1;
972 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
973 else if (this.drawOffer == "threerep") this.drawOffer = "";
974 if (!!this.game.mycolor && !data.receiveMyMove) {
975 // NOTE: 'var' to see that variable outside this block
976 var filtered_move = getFilteredMove(move);
977 }
978 // Since corr games are stored at only one location, update should be
979 // done only by one player for each move:
980 if (
981 !!this.game.mycolor &&
982 !data.receiveMyMove &&
983 (this.game.type == "live" || moveCol == this.game.mycolor)
984 ) {
985 let drawCode = "";
986 switch (this.drawOffer) {
987 case "threerep":
988 drawCode = "t";
989 break;
990 case "sent":
991 drawCode = this.game.mycolor;
992 break;
993 case "received":
994 drawCode = V.GetOppCol(this.game.mycolor);
995 break;
996 }
997 if (this.game.type == "corr") {
998 // corr: only move, fen and score
999 this.updateCorrGame({
1000 fen: this.game.fen,
1001 move: {
1002 squares: filtered_move,
1003 played: Date.now(),
1004 idx: origMovescount
1005 },
1006 // Code "n" for "None" to force reset (otherwise it's ignored)
1007 drawOffer: drawCode || "n"
1008 });
1009 }
1010 else {
1011 const updateStorage = () => {
1012 GameStorage.update(this.gameRef.id, {
1013 fen: this.game.fen,
1014 move: filtered_move,
1015 moveIdx: origMovescount,
1016 clocks: this.game.clocks,
1017 initime: this.game.initime,
1018 drawOffer: drawCode
1019 });
1020 };
1021 // The active tab can update storage immediately
1022 if (!document.hidden) updateStorage();
1023 // Small random delay otherwise
1024 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1025 }
1026 }
1027 // Send move ("newmove" event) to people in the room (if our turn)
1028 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1029 const sendMove = {
1030 move: filtered_move,
1031 index: origMovescount,
1032 // color is required to check if this is my move (if several tabs opened)
1033 color: moveCol,
1034 addTime: addTime, //undefined for corr games
1035 cancelDrawOffer: this.drawOffer == ""
1036 };
1037 this.opponentGotMove = false;
1038 this.send("newmove", {data: sendMove});
1039 // If the opponent doesn't reply gotmove soon enough, re-send move:
1040 this.retrySendmove = setInterval(
1041 () => {
1042 if (this.opponentGotMove) {
1043 clearInterval(this.retrySendmove);
1044 return;
1045 }
1046 let oppsid = this.game.players[nextIdx].sid;
1047 if (!oppsid) {
1048 oppsid = Object.keys(this.people).find(
1049 sid => this.people[sid].id == this.game.players[nextIdx].uid
1050 );
1051 }
1052 if (!oppsid || !this.people[oppsid])
1053 // Opponent is disconnected: he'll ask last state
1054 clearInterval(this.retrySendmove);
1055 else this.send("newmove", {data: sendMove, target: oppsid});
1056 },
1057 1000
1058 );
1059 }
1060 };
1061 if (
1062 this.game.type == "corr" &&
1063 moveCol == this.game.mycolor &&
1064 !data.receiveMyMove
1065 ) {
1066 const afterSetScore = () => {
1067 doProcessMove();
1068 if (this.st.settings.gotonext && this.nextIds.length > 0)
1069 this.showNextGame();
1070 else {
1071 this.re_setClocks();
1072 // The board might have been hidden:
1073 let boardDiv = document.querySelector(".game");
1074 if (boardDiv.style.visibility == "hidden")
1075 boardDiv.style.visibility = "visible";
1076 }
1077 };
1078 if (["all","byrow"].includes(V.ShowMoves)) {
1079 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1080 // We may play several moves in a row: in case of, remove listener:
1081 let elClone = el.cloneNode(true);
1082 el.parentNode.replaceChild(elClone, el);
1083 elClone.addEventListener(
1084 "click",
1085 () => {
1086 document.getElementById("modalConfirm").checked = false;
1087 if (!!data.score && data.score != "*")
1088 // Set score first
1089 this.gameOver(data.score, null, afterSetScore);
1090 else afterSetScore();
1091 }
1092 );
1093 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1094 V.PlayOnBoard(this.vr.board, move);
1095 const position = this.vr.getBaseFen();
1096 V.UndoOnBoard(this.vr.board, move);
1097 this.curDiag = getDiagram({
1098 position: position,
1099 orientation: V.CanFlip ? this.game.mycolor : "w"
1100 });
1101 document.getElementById("modalConfirm").checked = true;
1102 } else {
1103 // Incomplete information: just ask confirmation
1104 // Hide the board, because otherwise it could be revealed (TODO?)
1105 let boardDiv = document.querySelector(".game");
1106 boardDiv.style.visibility = "hidden";
1107 if (
1108 !confirm(
1109 this.st.tr["Move played:"] + " " +
1110 getFullNotation(move) + "\n" +
1111 this.st.tr["Are you sure?"]
1112 )
1113 ) {
1114 this.$refs["basegame"].cancelLastMove();
1115 boardDiv.style.visibility = "visible";
1116 return;
1117 }
1118 if (!!data.score && data.score != "*")
1119 this.gameOver(data.score, null, afterSetScore);
1120 else afterSetScore();
1121 }
1122 }
1123 else {
1124 // Normal situation
1125 const afterSetScore = () => {
1126 doProcessMove();
1127 this.re_setClocks();
1128 };
1129 if (!!data.score && data.score != "*")
1130 this.gameOver(data.score, null, afterSetScore);
1131 else afterSetScore();
1132 }
1133 },
1134 cancelMove: function() {
1135 document.getElementById("modalConfirm").checked = false;
1136 this.$refs["basegame"].cancelLastMove();
1137 },
1138 // In corr games, callback to change page only after score is set:
1139 gameOver: function(score, scoreMsg, callback) {
1140 this.game.score = score;
1141 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1142 this.$set(this.game, "scoreMsg", scoreMsg);
1143 const myIdx = this.game.players.findIndex(p => {
1144 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1145 });
1146 if (myIdx >= 0) {
1147 // OK, I play in this game
1148 const scoreObj = {
1149 score: score,
1150 scoreMsg: scoreMsg
1151 };
1152 if (this.game.type == "live") {
1153 GameStorage.update(this.gameRef.id, scoreObj);
1154 if (!!callback) callback();
1155 }
1156 else this.updateCorrGame(scoreObj, callback);
1157 // Notify the score to main Hall. TODO: only one player (currently double send)
1158 this.send("result", { gid: this.game.id, score: score });
1159 }
1160 else if (!!callback) callback();
1161 }
1162 }
1163 };
1164 </script>
1165
1166 <style lang="sass" scoped>
1167 .connected
1168 background-color: lightgreen
1169
1170 #participants
1171 margin-left: 5px
1172
1173 .anonymous
1174 color: grey
1175 font-style: italic
1176
1177 #playersInfo > p
1178 margin: 0
1179
1180 @media screen and (min-width: 768px)
1181 #actions
1182 width: 300px
1183 @media screen and (max-width: 767px)
1184 .game
1185 width: 100%
1186
1187 #actions
1188 display: inline-block
1189 margin: 0
1190
1191 button
1192 display: inline-block
1193 margin: 0
1194 display: inline-flex
1195 img
1196 height: 24px
1197 display: flex
1198 @media screen and (max-width: 767px)
1199 height: 18px
1200
1201 @media screen and (max-width: 767px)
1202 #aboveBoard
1203 text-align: center
1204 @media screen and (min-width: 768px)
1205 #aboveBoard
1206 margin-left: 30%
1207
1208 .variant-cadence
1209 padding-right: 10px
1210
1211 .variant-name
1212 font-weight: bold
1213 padding-right: 10px
1214
1215 span#nextGame
1216 background-color: #edda99
1217 cursor: pointer
1218 display: inline-block
1219 margin-right: 10px
1220
1221 span.name
1222 font-size: 1.5rem
1223 padding: 0 3px
1224
1225 span.time
1226 font-size: 2rem
1227 display: inline-block
1228 .time-left
1229 margin-left: 10px
1230 .time-right
1231 margin-left: 5px
1232 .time-separator
1233 margin-left: 5px
1234 position: relative
1235 top: -1px
1236
1237 span.yourturn
1238 color: #831B1B
1239 .time-separator
1240 animation: blink-animation 2s steps(3, start) infinite
1241 @keyframes blink-animation
1242 to
1243 visibility: hidden
1244
1245 .split-names
1246 display: inline-block
1247 margin: 0 15px
1248
1249 #chatWrap > .card
1250 padding-top: 20px
1251 max-width: 767px
1252 border: none
1253
1254 #confirmDiv > .card
1255 max-width: 767px
1256 max-height: 100%
1257
1258 .draw-sent, .draw-sent:hover
1259 background-color: lightyellow
1260
1261 .draw-received, .draw-received:hover
1262 background-color: lightgreen
1263
1264 .draw-threerep, .draw-threerep:hover
1265 background-color: #e4d1fc
1266
1267 .somethingnew
1268 background-color: #c5fefe
1269
1270 .diagram
1271 margin: 0 auto
1272 max-width: 400px
1273 // width: 100% required for Firefox
1274 width: 100%
1275
1276 #buttonsConfirm
1277 margin: 0
1278 & > button > span
1279 width: 100%
1280 text-align: center
1281
1282 button.acceptBtn
1283 background-color: lightgreen
1284 button.refuseBtn
1285 background-color: red
1286 </style>