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