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