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