Fixes around game observing. TODO: abort/resign/draw + corr
[vchess.git] / client / src / views / Game.vue
CommitLineData
a6088c90
BA
1<template lang="pug">
2.row
3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
b988c726
BA
4 input#modalAbort.modal(type="checkbox")
5 div(role="dialog" aria-labelledby="abortBoxTitle")
6 .card.smallpad.small-modal.text-center
7 label.modal-close(for="modalAbort")
8 h3#abortBoxTitle.section {{ st.tr["Terminate game?"] }}
9 button(@click="abortGame") {{ st.tr["Sorry I have to go"] }}
10 button(@click="abortGame") {{ st.tr["Game seems over"] }}
b4fb1612
BA
11 BaseGame(:game="game" :vr="vr" ref="basegame"
12 @newmove="processMove" @gameover="gameOver")
f41ce580 13 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
afd3240d 14 div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
d4036efe 15 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
a6088c90 16 button(@click="offerDraw") Draw
b988c726 17 button(@click="() => abortGame()") Abort
a6088c90 18 button(@click="resign") Resign
9330b976 19 textarea(v-if="game.score=='*'" v-model="corrMsg")
5c8e044f 20 Chat(:players="game.players")
a6088c90
BA
21</template>
22
23<script>
46284a2f 24import BaseGame from "@/components/BaseGame.vue";
f21cd6d9 25import Chat from "@/components/Chat.vue";
a6088c90 26import { store } from "@/store";
967a2686 27import { GameStorage } from "@/utils/gameStorage";
5b87454c 28import { ppt } from "@/utils/datetime";
66d03f23 29import { extractTime } from "@/utils/timeControl";
f41ce580 30import { ArrayFun } from "@/utils/array";
a6088c90
BA
31
32export default {
33 name: 'my-game',
34 components: {
35 BaseGame,
5c8e044f 36 Chat,
a6088c90 37 },
f7121527 38 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
39 data: function() {
40 return {
41 st: store.state,
4b0384fa
BA
42 gameRef: { //given in URL (rid = remote ID)
43 id: "",
44 rid: ""
45 },
f41ce580 46 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
6fba6e0c 47 corrMsg: "", //to send offline messages in corr games
809ba2aa 48 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 49 vr: null, //"variant rules" object initialized from FEN
6fba6e0c 50 drawOffer: "", //TODO: use for button style
92a523d1 51 people: [], //players + observers
a6088c90
BA
52 };
53 },
54 watch: {
5f131484
BA
55 "$route": function(to, from) {
56 this.gameRef.id = to.params["id"];
57 this.gameRef.rid = to.query["rid"];
58 this.loadGame();
a6088c90 59 },
5b87454c 60 "game.clocks": function(newState) {
dce792f6
BA
61 if (this.game.moves.length < 2)
62 {
63 // 1st move not completed yet: freeze time
64 this.virtualClocks = newState.map(s => ppt(s));
65 return;
66 }
809ba2aa 67 const currentTurn = this.vr.turn;
6fba6e0c 68 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
69 let countdown = newState[colorIdx] -
70 (Date.now() - this.game.initime[colorIdx])/1000;
c0b27606
BA
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 });
809ba2aa 77 let clockUpdate = setInterval(() => {
e69f159d 78 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
809ba2aa
BA
79 {
80 clearInterval(clockUpdate);
e69f159d 81 if (countdown < 0)
809ba2aa
BA
82 {
83 this.$refs["basegame"].endGame(
e69f159d 84 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
809ba2aa
BA
85 }
86 }
9aa229f3
BA
87 else
88 {
89 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
90 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
91 }
809ba2aa 92 }, 1000);
5b87454c 93 },
92a523d1 94 },
5f131484 95 // TODO: redundant code with Hall.vue (related to people array)
a6088c90 96 created: function() {
5f131484
BA
97 // Always add myself to players' list
98 const my = this.st.user;
99 this.people.push({sid:my.sid, id:my.id, name:my.name});
dc284d90
BA
100 this.gameRef.id = this.$route.params["id"];
101 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
102 if (!this.gameRef.rid)
103 this.loadGame(); //local or corr: can load from now
afd3240d
BA
104 // TODO: mode analyse (/analyze/Atomic/rn
105 // ... fen = query[], vname=params[] ...
5f131484 106 // 0.1] Ask server for room composition:
dc284d90
BA
107 const initialize = () => {
108 // Poll clients + load game if stored remotely
5f131484 109 this.st.conn.send(JSON.stringify({code:"pollclients"}));
dc284d90
BA
110 if (!!this.gameRef.rid)
111 this.loadGame();
5f131484
BA
112 };
113 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
dc284d90 114 initialize();
5f131484 115 else //socket not ready yet (initial loading)
dc284d90 116 this.st.conn.onopen = initialize;
5f131484 117 this.st.conn.onmessage = this.socketMessageListener;
cdb34c93
BA
118 const socketCloseListener = () => {
119 store.socketCloseListener(); //reinitialize connexion (in store.js)
a9b131f1 120 this.st.conn.addEventListener('message', this.socketMessageListener);
cdb34c93
BA
121 this.st.conn.addEventListener('close', socketCloseListener);
122 };
cdb34c93
BA
123 this.st.conn.onclose = socketCloseListener;
124 },
125 methods: {
5f131484
BA
126 getOppSid: function() {
127 if (!!this.game.oppsid)
128 return this.game.oppsid;
129 const opponent = this.people.find(p => p.id == this.game.oppid);
130 return (!!opponent ? opponent.sid : null);
131 },
cdb34c93 132 socketMessageListener: function(msg) {
a6088c90 133 const data = JSON.parse(msg.data);
a6088c90
BA
134 switch (data.code)
135 {
5f131484
BA
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 {
f41ce580 159 let player = this.people.find(p => p.sid == data.user.sid);
cd0d7743
BA
160 // NOTE: sometimes player.id fails because player is undefined...
161 // Probably because the event was meant for Hall?
162 if (!player)
163 return;
f41ce580
BA
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)
411d23cd 168 {
f41ce580 169 // Send our "last state" informations to opponent
411d23cd
BA
170 const L = this.game.moves.length;
171 this.st.conn.send(JSON.stringify({
172 code: "lastate",
f41ce580
BA
173 target: player.sid,
174 state:
175 {
176 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
177 score: this.game.score,
178 movesCount: L,
179 drawOffer: this.drawOffer,
180 clocks: this.game.clocks,
181 }
411d23cd
BA
182 }));
183 }
a6088c90 184 break;
6fba6e0c 185 }
c6788ecf
BA
186 case "askgame":
187 // Send current (live) game
188 const myGame =
189 {
190 // Minimal game informations:
191 id: this.game.id,
ab6f48ea 192 players: this.game.players.map(p => { return {name:p.name}; }),
c6788ecf
BA
193 vid: this.game.vid,
194 timeControl: this.game.timeControl,
195 };
196 this.st.conn.send(JSON.stringify({code:"game",
197 game:myGame, target:data.from}));
198 break;
f41ce580
BA
199 case "newmove":
200 // NOTE: this call to play() will trigger processMove()
201 this.$refs["basegame"].play(data.move,
202 "receive", this.game.vname!="Dark" ? "animate" : null);
203 break;
a6088c90 204 case "lastate": //got opponent infos about last move
6fba6e0c
BA
205 {
206 const L = this.game.moves.length;
6fba6e0c 207 if (data.movesCount > L)
a6088c90 208 {
6fba6e0c 209 // Just got last move from him
f41ce580
BA
210 this.$refs["basegame"].play(data.lastMove,
211 "receive", this.game.vname!="Dark" ? "animate" : null);
6fba6e0c
BA
212 if (data.score != "*" && this.game.score == "*")
213 {
214 // Opponent resigned or aborted game, or accepted draw offer
215 // (this is not a stalemate or checkmate)
216 this.$refs["basegame"].endGame(data.score, "Opponent action");
217 }
f41ce580
BA
218 this.game.clocks = data.clocks; //TODO: check this?
219 this.drawOffer = data.drawOffer; //does opponent offer draw?
a6088c90 220 }
a6088c90 221 break;
6fba6e0c 222 }
93d1d7a7
BA
223 case "resign":
224 this.$refs["basegame"].endGame(
225 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
226 break;
93d1d7a7
BA
227 case "abort":
228 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
229 break;
2cc10cdb
BA
230 case "draw":
231 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
232 break;
233 case "drawoffer":
234 this.drawOffer = "received";
235 break;
7e1a1fe9 236 case "askfullgame":
dc284d90
BA
237 // TODO: use data.id to retrieve game in indexedDB (but for now only one running game so OK)
238 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
7e1a1fe9 239 break;
5f131484 240 case "fullgame":
5f131484
BA
241 this.loadGame(data.game);
242 break;
243 // TODO: drawaccepted (click draw button before sending move
244 // ==> draw offer in move)
245 // ==> on "newmove", check "drawOffer" field
246 case "connect":
247 {
c6788ecf
BA
248 this.people.push({name:"", id:0, sid:data.from});
249 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
5f131484
BA
250 break;
251 }
252 case "disconnect":
c6788ecf 253 ArrayFun.remove(this.people, p => p.sid == data.from);
a6088c90
BA
254 break;
255 }
cdb34c93 256 },
a6088c90 257 offerDraw: function() {
2cc10cdb 258 // TODO: also for corr games
6fba6e0c
BA
259 if (this.drawOffer == "received")
260 {
2cc10cdb 261 if (!confirm("Accept draw?"))
6fba6e0c 262 return;
5f131484
BA
263 const oppsid = this.getOppSid();
264 if (!!oppsid)
265 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
2cc10cdb
BA
266 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
267 }
6fba6e0c
BA
268 else if (this.drawOffer == "sent")
269 this.drawOffer = "";
270 else
271 {
272 if (!confirm("Offer draw?"))
273 return;
5f131484
BA
274 const oppsid = this.getOppSid();
275 if (!!oppsid)
276 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
a6088c90
BA
277 }
278 },
279 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
280 receiveDrawOffer: function() {
281 //if (...)
282 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
283 // if accept: send message "draw"
284 },
b988c726 285 abortGame: function(event) {
9aa229f3 286 let modalBox = document.getElementById("modalAbort");
b988c726
BA
287 if (!event)
288 {
289 // First call show options:
b988c726
BA
290 modalBox.checked = true;
291 }
292 else
293 {
9aa229f3
BA
294 modalBox.checked = false; //decision made: box disappear
295 const message = event.target.innerText;
d4036efe 296 // Next line will trigger a "gameover" event, bubbling up till here
9aa229f3 297 this.$refs["basegame"].endGame("?", "Abort: " + message);
5f131484
BA
298 const oppsid = this.getOppSid();
299 if (!!oppsid)
300 {
301 this.st.conn.send(JSON.stringify({
302 code: "abort",
303 msg: message,
304 target: oppsid,
305 }));
306 }
b988c726 307 }
a6088c90
BA
308 },
309 resign: function(e) {
310 if (!confirm("Resign the game?"))
311 return;
5f131484
BA
312 const oppsid = this.getOppSid();
313 if (!!oppsid)
314 {
315 this.st.conn.send(JSON.stringify({
316 code: "resign",
317 target: oppsid,
318 }));
319 }
93d1d7a7 320 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
321 this.$refs["basegame"].endGame(
322 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 323 },
967a2686
BA
324 // 3 cases for loading a game:
325 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
326 // - from server (one correspondance game I play[ed] or not)
327 // - from remote peer (one live game I don't play, finished or not)
967a2686
BA
328 loadGame: function(game) {
329 const afterRetrieval = async (game) => {
f41ce580
BA
330 const vModule = await import("@/variants/" + game.vname + ".js");
331 window.V = vModule.VariantRules;
332 this.vr = new V(game.fen);
c0b27606 333 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
92a523d1 334 const tc = extractTime(game.timeControl);
c0b27606
BA
335 if (gtype == "corr")
336 {
f41ce580
BA
337 if (game.players[0].color == "b")
338 {
339 // Adopt the same convention for live and corr games: [0] = white
340 [ game.players[0], game.players[1] ] =
341 [ game.players[1], game.players[0] ];
342 }
c0b27606 343 // corr game: needs to compute the clocks + initime
92a523d1 344 game.clocks = [tc.mainTime, tc.mainTime];
c0b27606 345 game.initime = [0, 0];
5f131484 346 const L = game.moves.length;
92b82def 347 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
5f131484 348 if (L >= 3)
92a523d1 349 {
5f131484
BA
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);
355 }
356 for (let i=0; i<=1; i++)
357 game.clocks[i] += addTime[i];
92a523d1 358 }
5f131484
BA
359 if (L >= 1)
360 game.initime[L%2] = game.moves[L-1].played;
92b82def 361 // Now that we used idx and played, re-format moves as for live games
6d68309a 362 game.moves = game.moves.map( (m) => {
92b82def 363 const s = m.squares;
6d68309a 364 return {
92b82def
BA
365 appear: s.appear,
366 vanish: s.vanish,
367 start: s.start,
368 end: s.end,
369 message: m.message,
370 };
371 });
c0b27606 372 }
f41ce580
BA
373 const myIdx = game.players.findIndex(p => {
374 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
375 });
92a523d1 376 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
66d03f23
BA
377 {
378 game.clocks = [tc.mainTime, tc.mainTime];
379 game.initime[0] = Date.now();
92a523d1 380 if (myIdx >= 0)
22efa391 381 {
cf742aaf 382 // I play in this live game; corr games don't have clocks+initime
d18bfa12 383 GameStorage.update(game.id,
22efa391
BA
384 {
385 clocks: game.clocks,
386 initime: game.initime,
387 });
388 }
66d03f23 389 }
4b0384fa
BA
390 this.game = Object.assign({},
391 game,
cf742aaf 392 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 393 {
c0b27606 394 type: gtype,
66d03f23 395 increment: tc.increment,
6fba6e0c 396 mycolor: [undefined,"w","b"][myIdx+1],
5f131484
BA
397 // opponent sid not strictly required (or available), but easier
398 // at least oppsid or oppid is available anyway:
399 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
400 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
6fba6e0c 401 }
4b0384fa 402 );
967a2686
BA
403 };
404 if (!!game)
dc284d90 405 return afterRetrieval(game);
967a2686
BA
406 if (!!this.gameRef.rid)
407 {
f41ce580 408 // Remote live game
dc284d90
BA
409 // (TODO: send game ID as well, and receiver would pick the corresponding
410 // game in his current games; if allowed to play several)
5f131484
BA
411 this.st.conn.send(JSON.stringify(
412 {code:"askfullgame", target:this.gameRef.rid}));
967a2686 413 // (send moves updates + resign/abort/draw actions)
967a2686
BA
414 }
415 else
416 {
f41ce580 417 // Local or corr game
11667c79 418 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 419 }
a6088c90 420 },
9d54ab89 421 // Post-process a move (which was just played)
ce87ac6a 422 processMove: function(move) {
b4fb1612
BA
423 if (!this.game.mycolor)
424 return; //I'm just an observer
9d54ab89 425 // Update storage (corr or live)
6fba6e0c 426 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89
BA
427 // https://stackoverflow.com/a/38750895
428 const allowed_fields = ["appear", "vanish", "start", "end"];
429 const filtered_move = Object.keys(move)
430 .filter(key => allowed_fields.includes(key))
431 .reduce((obj, key) => {
8a7452b5 432 obj[key] = move[key];
9d54ab89
BA
433 return obj;
434 }, {});
dc284d90 435 // Send move ("newmove" event) to people in the room (if our turn)
dce792f6 436 let addTime = 0;
9d54ab89 437 if (move.color == this.game.mycolor)
b4fb1612 438 {
dce792f6
BA
439 if (this.game.moves.length >= 2) //after first move
440 {
441 const elapsed = Date.now() - this.game.initime[colorIdx];
442 // elapsed time is measured in milliseconds
443 addTime = this.game.increment - elapsed/1000;
444 }
6d68309a
BA
445 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
446 if (this.game.type == "corr")
447 sendMove.message = this.corrMsg;
a4480041 448 const oppsid = this.getOppSid();
dc284d90
BA
449 this.people.forEach(p => {
450 if (p.sid != this.st.user.sid)
451 {
452 this.st.conn.send(JSON.stringify({
453 code: "newmove",
454 target: p.sid,
455 move: sendMove,
456 }));
457 }
458 });
a4480041
BA
459 if (this.game.type == "corr" && this.corrMsg != "")
460 {
461 // Add message to last move in BaseGame:
462 // TODO: not very good style...
463 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
464 }
b4fb1612 465 }
5b87454c
BA
466 else
467 addTime = move.addTime; //supposed transmitted
6fba6e0c 468 const nextIdx = ["w","b"].indexOf(this.vr.turn);
6d68309a
BA
469 // Since corr games are stored at only one location, update should be
470 // done only by one player for each move:
471 if (this.game.type == "live" || move.color == this.game.mycolor)
967a2686 472 {
e69f159d 473 if (this.game.type == "corr")
f41ce580 474 {
e69f159d 475 GameStorage.update(this.gameRef.id,
6d68309a 476 {
e69f159d
BA
477 fen: move.fen,
478 move:
479 {
480 squares: filtered_move,
481 message: this.corrMsg,
482 played: Date.now(), //TODO: on server?
483 idx: this.game.moves.length,
484 },
485 });
486 }
487 else //live
488 {
489 GameStorage.update(this.gameRef.id,
490 {
491 fen: move.fen,
492 move: filtered_move,
493 clocks: this.game.clocks.map((t,i) => i==colorIdx
494 ? this.game.clocks[i] + addTime
495 : this.game.clocks[i]),
496 initime: this.game.initime.map((t,i) => i==nextIdx
497 ? Date.now()
498 : this.game.initime[i]),
499 });
500 }
6d68309a 501 }
967a2686
BA
502 // Also update current game object:
503 this.game.moves.push(move);
504 this.game.fen = move.fen;
66d03f23
BA
505 //TODO: just this.game.clocks[colorIdx] += addTime;
506 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
809ba2aa 507 this.game.initime[nextIdx] = Date.now();
6d68309a
BA
508 // Finally reset curMoveMessage if needed
509 if (this.game.type == "corr" && move.color == this.game.mycolor)
510 this.corrMsg = "";
b4fb1612
BA
511 },
512 gameOver: function(score) {
93d1d7a7 513 this.game.mode = "analyze";
d18bfa12 514 this.game.score = score;
ab6f48ea
BA
515 const myIdx = this.game.players.findIndex(p => {
516 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
517 });
518 if (myIdx >= 0) //OK, I play in this game
519 GameStorage.update(this.gameRef.id, { score: score });
ce87ac6a 520 },
a6088c90
BA
521 },
522};
523</script>
7e1a1fe9
BA
524
525<style lang="sass">
526// TODO
527</style>