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