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