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