Work on sizes, CSS
[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 .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 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
17 div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
18 BaseGame(:game="game" :vr="vr" ref="basegame"
19 @newmove="processMove" @gameover="gameOver")
20 </template>
21
22 <script>
23 import BaseGame from "@/components/BaseGame.vue";
24 import Chat from "@/components/Chat.vue";
25 import { store } from "@/store";
26 import { GameStorage } from "@/utils/gameStorage";
27 import { ppt } from "@/utils/datetime";
28 import { extractTime } from "@/utils/timeControl";
29 import { ArrayFun } from "@/utils/array";
30
31 export default {
32 name: 'my-game',
33 components: {
34 BaseGame,
35 Chat,
36 },
37 // gameRef: to find the game in (potentially remote) storage
38 data: function() {
39 return {
40 st: store.state,
41 gameRef: { //given in URL (rid = remote ID)
42 id: "",
43 rid: ""
44 },
45 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
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.gameOver(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.$set(this.game, "moveToPlay", data.move); //TODO: Vue3...
203 break;
204 case "lastate": //got opponent infos about last move
205 {
206 this.lastate = data;
207 if (!!this.game.type) //game is loaded
208 this.processLastate();
209 //else: will be processed when game is ready
210 break;
211 }
212 case "resign":
213 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
214 break;
215 case "abort":
216 this.gameOver("?", "Abort");
217 break;
218 case "draw":
219 this.gameOver("1/2", "Mutual agreement");
220 break;
221 case "drawoffer":
222 this.drawOffer = "received"; //TODO: observers don't know who offered draw
223 break;
224 case "askfullgame":
225 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
226 break;
227 case "fullgame":
228 // Callback "roomInit" to poll clients only after game is loaded
229 this.loadGame(data.game, this.roomInit);
230 break;
231 case "connect":
232 {
233 this.people.push({name:"", id:0, sid:data.from});
234 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
235 break;
236 }
237 case "disconnect":
238 ArrayFun.remove(this.people, p => p.sid == data.from);
239 break;
240 }
241 },
242 // lastate was received, but maybe game wasn't ready yet:
243 processLastate: function() {
244 const data = this.lastate;
245 this.lastate = undefined; //security...
246 const L = this.game.moves.length;
247 if (data.movesCount > L)
248 {
249 // Just got last move from him
250 this.$set(this.game, "moveToPlay", data.lastMove);
251 if (data.score != "*" && this.game.score == "*")
252 {
253 // Opponent resigned or aborted game, or accepted draw offer
254 // (this is not a stalemate or checkmate)
255 this.gameOver(data.score, "Opponent action");
256 }
257 this.game.clocks = data.clocks; //TODO: check this?
258 if (!!data.lastMove.draw)
259 this.drawOffer = "received";
260 }
261 },
262 offerDraw: function() {
263 if (["received","threerep"].includes(this.drawOffer))
264 {
265 if (!confirm("Accept draw?"))
266 return;
267 this.people.forEach(p => {
268 if (p.sid != this.st.user.sid)
269 this.st.conn.send(JSON.stringify({code:"draw", target:p.sid}));
270 });
271 const message = (this.drawOffer == "received"
272 ? "Mutual agreement"
273 : "Three repetitions");
274 this.gameOver("1/2", message);
275 }
276 else if (this.drawOffer == "sent")
277 {
278 this.drawOffer = "";
279 if (this.game.type == "corr")
280 GameStorage.update(this.gameRef.id, {drawOffer: false});
281 }
282 else
283 {
284 if (!confirm("Offer draw?"))
285 return;
286 this.drawOffer = "sent";
287 this.people.forEach(p => {
288 if (p.sid != this.st.user.sid)
289 this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid}));
290 });
291 if (this.game.type == "corr")
292 GameStorage.update(this.gameRef.id, {drawOffer: true});
293 }
294 },
295 abortGame: function() {
296 if (!confirm(this.st.tr["Terminate game?"]))
297 return;
298 this.gameOver("?", "Abort");
299 this.people.forEach(p => {
300 if (p.sid != this.st.user.sid)
301 {
302 this.st.conn.send(JSON.stringify({
303 code: "abort",
304 target: p.sid,
305 }));
306 }
307 });
308 },
309 resign: function(e) {
310 if (!confirm("Resign the game?"))
311 return;
312 this.people.forEach(p => {
313 if (p.sid != this.st.user.sid)
314 {
315 this.st.conn.send(JSON.stringify({code:"resign",
316 side:this.game.mycolor, target:p.sid}));
317 }
318 });
319 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
320 },
321 // 3 cases for loading a game:
322 // - from indexedDB (running or completed live game I play)
323 // - from server (one correspondance game I play[ed] or not)
324 // - from remote peer (one live game I don't play, finished or not)
325 loadGame: function(game, callback) {
326 const afterRetrieval = async (game) => {
327 const vModule = await import("@/variants/" + game.vname + ".js");
328 window.V = vModule.VariantRules;
329 this.vr = new V(game.fen);
330 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
331 const tc = extractTime(game.timeControl);
332 if (gtype == "corr")
333 {
334 if (game.players[0].color == "b")
335 {
336 // Adopt the same convention for live and corr games: [0] = white
337 [ game.players[0], game.players[1] ] =
338 [ game.players[1], game.players[0] ];
339 }
340 // corr game: needs to compute the clocks + initime
341 // NOTE: clocks in seconds, initime in milliseconds
342 game.clocks = [tc.mainTime, tc.mainTime];
343 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
344 if (game.score == "*") //otherwise no need to bother with time
345 {
346 game.initime = [0, 0];
347 const L = game.moves.length;
348 if (L >= 3)
349 {
350 let addTime = [0, 0];
351 for (let i=2; i<L; i++)
352 {
353 addTime[i%2] += tc.increment -
354 (game.moves[i].played - game.moves[i-1].played) / 1000;
355 }
356 for (let i=0; i<=1; i++)
357 game.clocks[i] += addTime[i];
358 }
359 if (L >= 1)
360 game.initime[L%2] = game.moves[L-1].played;
361 if (game.drawOffer)
362 this.drawOffer = "received";
363 }
364 // Now that we used idx and played, re-format moves as for live games
365 game.moves = game.moves.map( (m) => {
366 const s = m.squares;
367 return {
368 appear: s.appear,
369 vanish: s.vanish,
370 start: s.start,
371 end: s.end,
372 };
373 });
374 // Also sort chat messages (if any)
375 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
376 }
377 const myIdx = game.players.findIndex(p => {
378 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
379 });
380 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
381 {
382 game.clocks = [tc.mainTime, tc.mainTime];
383 if (game.score == "*")
384 {
385 game.initime[0] = Date.now();
386 if (myIdx >= 0)
387 {
388 // I play in this live game; corr games don't have clocks+initime
389 GameStorage.update(game.id,
390 {
391 clocks: game.clocks,
392 initime: game.initime,
393 });
394 }
395 }
396 }
397 this.game = Object.assign({},
398 game,
399 // NOTE: assign mycolor here, since BaseGame could also be VS computer
400 {
401 type: gtype,
402 increment: tc.increment,
403 mycolor: [undefined,"w","b"][myIdx+1],
404 // opponent sid not strictly required (or available), but easier
405 // at least oppsid or oppid is available anyway:
406 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
407 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
408 }
409 );
410 this.repeat = {}; //reset
411 if (!!this.lastate) //lastate arrived before game was loaded:
412 this.processLastate();
413 callback();
414 };
415 if (!!game)
416 return afterRetrieval(game);
417 if (!!this.gameRef.rid)
418 {
419 // Remote live game: forgetting about callback func... (TODO: design)
420 this.st.conn.send(JSON.stringify(
421 {code:"askfullgame", target:this.gameRef.rid}));
422 }
423 else
424 {
425 // Local or corr game
426 GameStorage.get(this.gameRef.id, afterRetrieval);
427 }
428 },
429 // Post-process a move (which was just played)
430 processMove: function(move) {
431 // Update storage (corr or live) if I play in the game
432 const colorIdx = ["w","b"].indexOf(move.color);
433 // https://stackoverflow.com/a/38750895
434 if (!!this.game.mycolor)
435 {
436 const allowed_fields = ["appear", "vanish", "start", "end"];
437 // NOTE: 'var' to see this variable outside this block
438 var 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 }
445 // Send move ("newmove" event) to people in the room (if our turn)
446 let addTime = 0;
447 if (move.color == this.game.mycolor)
448 {
449 if (this.game.moves.length >= 2) //after first move
450 {
451 const elapsed = Date.now() - this.game.initime[colorIdx];
452 // elapsed time is measured in milliseconds
453 addTime = this.game.increment - elapsed/1000;
454 }
455 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
456 this.people.forEach(p => {
457 if (p.sid != this.st.user.sid)
458 {
459 this.st.conn.send(JSON.stringify({
460 code: "newmove",
461 target: p.sid,
462 move: sendMove,
463 }));
464 }
465 });
466 }
467 else
468 addTime = move.addTime; //supposed transmitted
469 const nextIdx = ["w","b"].indexOf(this.vr.turn);
470 // Since corr games are stored at only one location, update should be
471 // done only by one player for each move:
472 if (!!this.game.mycolor &&
473 (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 move:
481 {
482 squares: filtered_move,
483 played: Date.now(), //TODO: on server?
484 idx: this.game.moves.length,
485 },
486 });
487 }
488 else //live
489 {
490 GameStorage.update(this.gameRef.id,
491 {
492 fen: move.fen,
493 move: filtered_move,
494 clocks: this.game.clocks.map((t,i) => i==colorIdx
495 ? this.game.clocks[i] + addTime
496 : this.game.clocks[i]),
497 initime: this.game.initime.map((t,i) => i==nextIdx
498 ? Date.now()
499 : this.game.initime[i]),
500 });
501 }
502 }
503 // Also update current game object:
504 this.game.moves.push(move);
505 this.game.fen = move.fen;
506 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
507 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
508 this.game.initime[nextIdx] = Date.now();
509 // If repetition detected, consider that a draw offer was received:
510 const fenObj = V.ParseFen(move.fen);
511 let repIdx = fenObj.position + "_" + fenObj.turn;
512 if (!!fenObj.flags)
513 repIdx += "_" + fenObj.flags;
514 this.repeat[repIdx] = (!!this.repeat[repIdx]
515 ? this.repeat[repIdx]+1
516 : 1);
517 if (this.repeat[repIdx] >= 3)
518 this.drawOffer = "threerep";
519 },
520 toggleChat: function() {
521 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
522 },
523 finishSendChat: function(chat) {
524 if (this.game.type == "corr")
525 GameStorage.update(this.gameRef.id, {chat: chat});
526 },
527 processChat: function() {
528 if (!document.getElementById("inputChat").checked)
529 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
530 },
531 gameOver: function(score, scoreMsg) {
532 this.game.mode = "analyze";
533 this.game.score = score;
534 this.game.scoreMsg = scoreMsg;
535 const myIdx = this.game.players.findIndex(p => {
536 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
537 });
538 if (myIdx >= 0) //OK, I play in this game
539 GameStorage.update(this.gameRef.id, { score: score });
540 },
541 },
542 };
543 </script>
544
545 <style lang="sass">
546 .connected
547 background-color: green
548 .disconnected
549 background-color: red
550
551 @media screen and (min-width: 768px)
552 #actions
553 width: 300px
554 @media screen and (max-width: 767px)
555 .game
556 width: 100%
557
558 #actions
559 display: inline-block
560 margin-top: 10px
561 button
562 display: inline-block
563 width: 33%
564 margin: 0
565
566 #chat
567 padding-top: 20px
568 max-width: 600px
569 border: none;
570
571 #chatBtn
572 margin: 0 10px 0 0
573 </style>