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