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