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