Advance on draw logic (for live, not 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
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 {
6d9f4315
BA
127 case "duplicate":
128 alert("Warning: duplicate 'offline' connection");
129 break;
5f131484
BA
130 // 0.2] Receive clients list (just socket IDs)
131 case "pollclients":
132 {
133 data.sockIds.forEach(sid => {
134 this.people.push({sid:sid, id:0, name:""});
135 // Ask only identity
136 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
137 });
138 break;
139 }
140 case "askidentity":
141 {
142 // Request for identification: reply if I'm not anonymous
143 if (this.st.user.id > 0)
144 {
145 this.st.conn.send(JSON.stringify(
146 // people[0] instead of st.user to avoid sending email
147 {code:"identity", user:this.people[0], target:data.from}));
148 }
149 break;
150 }
151 case "identity":
152 {
f41ce580 153 let player = this.people.find(p => p.sid == data.user.sid);
cd0d7743
BA
154 // NOTE: sometimes player.id fails because player is undefined...
155 // Probably because the event was meant for Hall?
156 if (!player)
157 return;
f41ce580
BA
158 player.id = data.user.id;
159 player.name = data.user.name;
160 // Sending last state only for live games: corr games are complete
161 if (this.game.type == "live" && this.game.oppsid == player.sid)
411d23cd 162 {
f41ce580 163 // Send our "last state" informations to opponent
411d23cd 164 const L = this.game.moves.length;
6d9f4315
BA
165 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
166 if (!!lastMove && this.drawOffer == "sent")
167 lastMove.draw = true;
411d23cd
BA
168 this.st.conn.send(JSON.stringify({
169 code: "lastate",
f41ce580
BA
170 target: player.sid,
171 state:
172 {
6d9f4315 173 lastMove: lastMove,
f41ce580
BA
174 score: this.game.score,
175 movesCount: L,
f41ce580
BA
176 clocks: this.game.clocks,
177 }
411d23cd
BA
178 }));
179 }
a6088c90 180 break;
6fba6e0c 181 }
c6788ecf
BA
182 case "askgame":
183 // Send current (live) game
184 const myGame =
185 {
186 // Minimal game informations:
187 id: this.game.id,
ab6f48ea 188 players: this.game.players.map(p => { return {name:p.name}; }),
c6788ecf
BA
189 vid: this.game.vid,
190 timeControl: this.game.timeControl,
191 };
192 this.st.conn.send(JSON.stringify({code:"game",
193 game:myGame, target:data.from}));
194 break;
f41ce580
BA
195 case "newmove":
196 // NOTE: this call to play() will trigger processMove()
197 this.$refs["basegame"].play(data.move,
198 "receive", this.game.vname!="Dark" ? "animate" : null);
199 break;
a6088c90 200 case "lastate": //got opponent infos about last move
6fba6e0c
BA
201 {
202 const L = this.game.moves.length;
6fba6e0c 203 if (data.movesCount > L)
a6088c90 204 {
6fba6e0c 205 // Just got last move from him
f41ce580
BA
206 this.$refs["basegame"].play(data.lastMove,
207 "receive", this.game.vname!="Dark" ? "animate" : null);
6fba6e0c
BA
208 if (data.score != "*" && this.game.score == "*")
209 {
210 // Opponent resigned or aborted game, or accepted draw offer
211 // (this is not a stalemate or checkmate)
212 this.$refs["basegame"].endGame(data.score, "Opponent action");
213 }
f41ce580 214 this.game.clocks = data.clocks; //TODO: check this?
6d9f4315
BA
215 if (!!data.lastMove.draw)
216 this.drawOffer = "received";
a6088c90 217 }
a6088c90 218 break;
6fba6e0c 219 }
93d1d7a7
BA
220 case "resign":
221 this.$refs["basegame"].endGame(
222 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
223 break;
93d1d7a7 224 case "abort":
7f3484bd 225 this.$refs["basegame"].endGame("?", "Abort");
93d1d7a7 226 break;
2cc10cdb
BA
227 case "draw":
228 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
229 break;
230 case "drawoffer":
231 this.drawOffer = "received";
232 break;
6d9f4315
BA
233 case "drawaccepted":
234 this.gameOver("1/2");
235 break;
7e1a1fe9 236 case "askfullgame":
dc284d90 237 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
7e1a1fe9 238 break;
5f131484 239 case "fullgame":
5f131484
BA
240 this.loadGame(data.game);
241 break;
5f131484
BA
242 case "connect":
243 {
c6788ecf
BA
244 this.people.push({name:"", id:0, sid:data.from});
245 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
5f131484
BA
246 break;
247 }
248 case "disconnect":
c6788ecf 249 ArrayFun.remove(this.people, p => p.sid == data.from);
a6088c90
BA
250 break;
251 }
cdb34c93 252 },
a6088c90 253 offerDraw: function() {
2cc10cdb 254 // TODO: also for corr games
6fba6e0c
BA
255 if (this.drawOffer == "received")
256 {
2cc10cdb 257 if (!confirm("Accept draw?"))
6fba6e0c 258 return;
6d9f4315 259 const oppsid = this.getOppSid(); //TODO: to all people...
5f131484
BA
260 if (!!oppsid)
261 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
2cc10cdb
BA
262 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
263 }
6fba6e0c
BA
264 else if (this.drawOffer == "sent")
265 this.drawOffer = "";
266 else
267 {
268 if (!confirm("Offer draw?"))
269 return;
5f131484
BA
270 const oppsid = this.getOppSid();
271 if (!!oppsid)
272 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
a6088c90
BA
273 }
274 },
7f3484bd
BA
275 abortGame: function() {
276 if (!confirm(this.st.tr["Terminate game?"]))
277 return;
278 // Next line will trigger a "gameover" event, bubbling up till here
279 this.$refs["basegame"].endGame("?", "Abort");
280 this.people.forEach(p => {
281 if (p.sid != this.st.user.sid)
5f131484
BA
282 {
283 this.st.conn.send(JSON.stringify({
284 code: "abort",
7f3484bd 285 target: p.sid,
5f131484
BA
286 }));
287 }
7f3484bd 288 });
a6088c90
BA
289 },
290 resign: function(e) {
291 if (!confirm("Resign the game?"))
292 return;
5f131484
BA
293 const oppsid = this.getOppSid();
294 if (!!oppsid)
295 {
296 this.st.conn.send(JSON.stringify({
297 code: "resign",
298 target: oppsid,
299 }));
300 }
93d1d7a7 301 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
302 this.$refs["basegame"].endGame(
303 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 304 },
967a2686
BA
305 // 3 cases for loading a game:
306 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
307 // - from server (one correspondance game I play[ed] or not)
308 // - from remote peer (one live game I don't play, finished or not)
967a2686
BA
309 loadGame: function(game) {
310 const afterRetrieval = async (game) => {
f41ce580
BA
311 const vModule = await import("@/variants/" + game.vname + ".js");
312 window.V = vModule.VariantRules;
313 this.vr = new V(game.fen);
c0b27606 314 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
92a523d1 315 const tc = extractTime(game.timeControl);
c0b27606
BA
316 if (gtype == "corr")
317 {
f41ce580
BA
318 if (game.players[0].color == "b")
319 {
320 // Adopt the same convention for live and corr games: [0] = white
321 [ game.players[0], game.players[1] ] =
322 [ game.players[1], game.players[0] ];
323 }
c0b27606 324 // corr game: needs to compute the clocks + initime
7f3484bd 325 // NOTE: clocks in seconds, initime in milliseconds
92a523d1 326 game.clocks = [tc.mainTime, tc.mainTime];
c0b27606 327 game.initime = [0, 0];
5f131484 328 const L = game.moves.length;
92b82def 329 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
5f131484 330 if (L >= 3)
92a523d1 331 {
5f131484
BA
332 let addTime = [0, 0];
333 for (let i=2; i<L; i++)
334 {
335 addTime[i%2] += tc.increment -
7f3484bd 336 (game.moves[i].played - game.moves[i-1].played) / 1000;
5f131484
BA
337 }
338 for (let i=0; i<=1; i++)
339 game.clocks[i] += addTime[i];
92a523d1 340 }
5f131484
BA
341 if (L >= 1)
342 game.initime[L%2] = game.moves[L-1].played;
92b82def 343 // Now that we used idx and played, re-format moves as for live games
6d68309a 344 game.moves = game.moves.map( (m) => {
92b82def 345 const s = m.squares;
6d68309a 346 return {
92b82def
BA
347 appear: s.appear,
348 vanish: s.vanish,
349 start: s.start,
350 end: s.end,
351 message: m.message,
352 };
353 });
c0b27606 354 }
f41ce580
BA
355 const myIdx = game.players.findIndex(p => {
356 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
357 });
92a523d1 358 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
66d03f23
BA
359 {
360 game.clocks = [tc.mainTime, tc.mainTime];
361 game.initime[0] = Date.now();
92a523d1 362 if (myIdx >= 0)
22efa391 363 {
cf742aaf 364 // I play in this live game; corr games don't have clocks+initime
d18bfa12 365 GameStorage.update(game.id,
22efa391
BA
366 {
367 clocks: game.clocks,
368 initime: game.initime,
369 });
370 }
66d03f23 371 }
4b0384fa
BA
372 this.game = Object.assign({},
373 game,
cf742aaf 374 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 375 {
c0b27606 376 type: gtype,
66d03f23 377 increment: tc.increment,
6fba6e0c 378 mycolor: [undefined,"w","b"][myIdx+1],
5f131484
BA
379 // opponent sid not strictly required (or available), but easier
380 // at least oppsid or oppid is available anyway:
381 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
382 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
6fba6e0c 383 }
4b0384fa 384 );
967a2686
BA
385 };
386 if (!!game)
dc284d90 387 return afterRetrieval(game);
967a2686
BA
388 if (!!this.gameRef.rid)
389 {
f41ce580 390 // Remote live game
dc284d90
BA
391 // (TODO: send game ID as well, and receiver would pick the corresponding
392 // game in his current games; if allowed to play several)
5f131484
BA
393 this.st.conn.send(JSON.stringify(
394 {code:"askfullgame", target:this.gameRef.rid}));
967a2686 395 // (send moves updates + resign/abort/draw actions)
967a2686
BA
396 }
397 else
398 {
f41ce580 399 // Local or corr game
11667c79 400 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 401 }
a6088c90 402 },
9d54ab89 403 // Post-process a move (which was just played)
ce87ac6a 404 processMove: function(move) {
b4fb1612
BA
405 if (!this.game.mycolor)
406 return; //I'm just an observer
9d54ab89 407 // Update storage (corr or live)
6fba6e0c 408 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89
BA
409 // https://stackoverflow.com/a/38750895
410 const allowed_fields = ["appear", "vanish", "start", "end"];
411 const filtered_move = Object.keys(move)
412 .filter(key => allowed_fields.includes(key))
413 .reduce((obj, key) => {
8a7452b5 414 obj[key] = move[key];
9d54ab89
BA
415 return obj;
416 }, {});
dc284d90 417 // Send move ("newmove" event) to people in the room (if our turn)
dce792f6 418 let addTime = 0;
9d54ab89 419 if (move.color == this.game.mycolor)
b4fb1612 420 {
dce792f6
BA
421 if (this.game.moves.length >= 2) //after first move
422 {
423 const elapsed = Date.now() - this.game.initime[colorIdx];
424 // elapsed time is measured in milliseconds
425 addTime = this.game.increment - elapsed/1000;
426 }
6d68309a
BA
427 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
428 if (this.game.type == "corr")
429 sendMove.message = this.corrMsg;
a4480041 430 const oppsid = this.getOppSid();
dc284d90
BA
431 this.people.forEach(p => {
432 if (p.sid != this.st.user.sid)
433 {
434 this.st.conn.send(JSON.stringify({
435 code: "newmove",
436 target: p.sid,
437 move: sendMove,
438 }));
439 }
440 });
a4480041
BA
441 if (this.game.type == "corr" && this.corrMsg != "")
442 {
443 // Add message to last move in BaseGame:
444 // TODO: not very good style...
445 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
446 }
b4fb1612 447 }
5b87454c
BA
448 else
449 addTime = move.addTime; //supposed transmitted
6fba6e0c 450 const nextIdx = ["w","b"].indexOf(this.vr.turn);
6d68309a
BA
451 // Since corr games are stored at only one location, update should be
452 // done only by one player for each move:
453 if (this.game.type == "live" || move.color == this.game.mycolor)
967a2686 454 {
e69f159d 455 if (this.game.type == "corr")
f41ce580 456 {
e69f159d 457 GameStorage.update(this.gameRef.id,
6d68309a 458 {
e69f159d
BA
459 fen: move.fen,
460 move:
461 {
462 squares: filtered_move,
463 message: this.corrMsg,
464 played: Date.now(), //TODO: on server?
465 idx: this.game.moves.length,
466 },
467 });
468 }
469 else //live
470 {
471 GameStorage.update(this.gameRef.id,
472 {
473 fen: move.fen,
474 move: filtered_move,
475 clocks: this.game.clocks.map((t,i) => i==colorIdx
476 ? this.game.clocks[i] + addTime
477 : this.game.clocks[i]),
478 initime: this.game.initime.map((t,i) => i==nextIdx
479 ? Date.now()
480 : this.game.initime[i]),
481 });
482 }
6d68309a 483 }
967a2686
BA
484 // Also update current game object:
485 this.game.moves.push(move);
486 this.game.fen = move.fen;
66d03f23
BA
487 //TODO: just this.game.clocks[colorIdx] += addTime;
488 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
809ba2aa 489 this.game.initime[nextIdx] = Date.now();
6d68309a
BA
490 // Finally reset curMoveMessage if needed
491 if (this.game.type == "corr" && move.color == this.game.mycolor)
492 this.corrMsg = "";
b4fb1612
BA
493 },
494 gameOver: function(score) {
93d1d7a7 495 this.game.mode = "analyze";
d18bfa12 496 this.game.score = score;
ab6f48ea
BA
497 const myIdx = this.game.players.findIndex(p => {
498 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
499 });
500 if (myIdx >= 0) //OK, I play in this game
501 GameStorage.update(this.gameRef.id, { score: score });
ce87ac6a 502 },
a6088c90
BA
503 },
504};
505</script>
7e1a1fe9
BA
506
507<style lang="sass">
508// TODO
509</style>