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