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