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