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