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