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