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