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