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