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