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