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