Finish corr implementation for draw offers (untested)
[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
760adbce 45 lastate: undefined, //used if opponent send lastate before game is ready
a6088c90
BA
46 };
47 },
48 watch: {
5f131484
BA
49 "$route": function(to, from) {
50 this.gameRef.id = to.params["id"];
51 this.gameRef.rid = to.query["rid"];
52 this.loadGame();
a6088c90 53 },
5b87454c 54 "game.clocks": function(newState) {
b7cbbda1 55 if (this.game.moves.length < 2 || this.game.score != "*")
dce792f6 56 {
b7cbbda1 57 // 1st move not completed yet, or game over: freeze time
dce792f6
BA
58 this.virtualClocks = newState.map(s => ppt(s));
59 return;
60 }
809ba2aa 61 const currentTurn = this.vr.turn;
6fba6e0c 62 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
63 let countdown = newState[colorIdx] -
64 (Date.now() - this.game.initime[colorIdx])/1000;
c0b27606
BA
65 this.virtualClocks = [0,1].map(i => {
66 const removeTime = i == colorIdx
67 ? (Date.now() - this.game.initime[colorIdx])/1000
68 : 0;
69 return ppt(newState[i] - removeTime);
70 });
809ba2aa 71 let clockUpdate = setInterval(() => {
e69f159d 72 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
809ba2aa
BA
73 {
74 clearInterval(clockUpdate);
e69f159d 75 if (countdown < 0)
809ba2aa
BA
76 {
77 this.$refs["basegame"].endGame(
e69f159d 78 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
809ba2aa
BA
79 }
80 }
9aa229f3
BA
81 else
82 {
83 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
84 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
85 }
809ba2aa 86 }, 1000);
5b87454c 87 },
92a523d1 88 },
5f131484 89 // TODO: redundant code with Hall.vue (related to people array)
a6088c90 90 created: function() {
5f131484
BA
91 // Always add myself to players' list
92 const my = this.st.user;
93 this.people.push({sid:my.sid, id:my.id, name:my.name});
dc284d90
BA
94 this.gameRef.id = this.$route.params["id"];
95 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
760adbce 96 // Define socket .onmessage() and .onclose() events:
5f131484 97 this.st.conn.onmessage = this.socketMessageListener;
cdb34c93
BA
98 const socketCloseListener = () => {
99 store.socketCloseListener(); //reinitialize connexion (in store.js)
a9b131f1 100 this.st.conn.addEventListener('message', this.socketMessageListener);
cdb34c93
BA
101 this.st.conn.addEventListener('close', socketCloseListener);
102 };
cdb34c93 103 this.st.conn.onclose = socketCloseListener;
760adbce
BA
104 // Socket init required before loading remote game:
105 const socketInit = (callback) => {
106 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
107 callback();
108 else //socket not ready yet (initial loading)
109 this.st.conn.onopen = callback;
110 };
111 if (!this.gameRef.rid) //game stored locally or on server
112 this.loadGame(null, () => socketInit(this.roomInit));
113 else //game stored remotely: need socket to retrieve it
114 {
115 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
116 // --> It will be given when receiving "fullgame" socket event.
117 // A more general approach would be to store it somewhere.
118 socketInit(this.loadGame);
119 }
cdb34c93
BA
120 },
121 methods: {
760adbce
BA
122 // O.1] Ask server for room composition:
123 roomInit: function() {
124 this.st.conn.send(JSON.stringify({code:"pollclients"}));
5f131484 125 },
cdb34c93 126 socketMessageListener: function(msg) {
a6088c90 127 const data = JSON.parse(msg.data);
a6088c90
BA
128 switch (data.code)
129 {
6d9f4315
BA
130 case "duplicate":
131 alert("Warning: duplicate 'offline' connection");
132 break;
5f131484
BA
133 // 0.2] Receive clients list (just socket IDs)
134 case "pollclients":
135 {
136 data.sockIds.forEach(sid => {
137 this.people.push({sid:sid, id:0, name:""});
138 // Ask only identity
139 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
140 });
141 break;
142 }
143 case "askidentity":
144 {
145 // Request for identification: reply if I'm not anonymous
146 if (this.st.user.id > 0)
147 {
148 this.st.conn.send(JSON.stringify(
149 // people[0] instead of st.user to avoid sending email
150 {code:"identity", user:this.people[0], target:data.from}));
151 }
152 break;
153 }
154 case "identity":
155 {
f41ce580 156 let player = this.people.find(p => p.sid == data.user.sid);
cd0d7743
BA
157 // NOTE: sometimes player.id fails because player is undefined...
158 // Probably because the event was meant for Hall?
159 if (!player)
160 return;
f41ce580
BA
161 player.id = data.user.id;
162 player.name = data.user.name;
163 // Sending last state only for live games: corr games are complete
164 if (this.game.type == "live" && this.game.oppsid == player.sid)
411d23cd 165 {
f41ce580 166 // Send our "last state" informations to opponent
411d23cd 167 const L = this.game.moves.length;
6d9f4315
BA
168 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
169 if (!!lastMove && this.drawOffer == "sent")
170 lastMove.draw = true;
411d23cd
BA
171 this.st.conn.send(JSON.stringify({
172 code: "lastate",
f41ce580
BA
173 target: player.sid,
174 state:
175 {
6d9f4315 176 lastMove: lastMove,
f41ce580
BA
177 score: this.game.score,
178 movesCount: L,
f41ce580
BA
179 clocks: this.game.clocks,
180 }
411d23cd
BA
181 }));
182 }
a6088c90 183 break;
6fba6e0c 184 }
c6788ecf
BA
185 case "askgame":
186 // Send current (live) game
187 const myGame =
188 {
189 // Minimal game informations:
190 id: this.game.id,
ab6f48ea 191 players: this.game.players.map(p => { return {name:p.name}; }),
c6788ecf
BA
192 vid: this.game.vid,
193 timeControl: this.game.timeControl,
194 };
195 this.st.conn.send(JSON.stringify({code:"game",
196 game:myGame, target:data.from}));
197 break;
f41ce580
BA
198 case "newmove":
199 // NOTE: this call to play() will trigger processMove()
200 this.$refs["basegame"].play(data.move,
201 "receive", this.game.vname!="Dark" ? "animate" : null);
202 break;
a6088c90 203 case "lastate": //got opponent infos about last move
6fba6e0c 204 {
760adbce
BA
205 this.lastate = data;
206 if (!!this.game.type) //game is loaded
207 this.processLastate();
208 //else: will be processed when game is ready
a6088c90 209 break;
6fba6e0c 210 }
93d1d7a7
BA
211 case "resign":
212 this.$refs["basegame"].endGame(
760adbce 213 (data.side=="b" ? "1-0" : "0-1"), "Resign");
93d1d7a7 214 break;
93d1d7a7 215 case "abort":
7f3484bd 216 this.$refs["basegame"].endGame("?", "Abort");
93d1d7a7 217 break;
2cc10cdb
BA
218 case "draw":
219 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
220 break;
221 case "drawoffer":
760adbce 222 this.drawOffer = "received"; //TODO: observers don't know who offered draw
6d9f4315 223 break;
7e1a1fe9 224 case "askfullgame":
dc284d90 225 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
7e1a1fe9 226 break;
5f131484 227 case "fullgame":
760adbce
BA
228 // Callback "roomInit" to poll clients only after game is loaded
229 this.loadGame(data.game, this.roomInit);
5f131484 230 break;
5f131484
BA
231 case "connect":
232 {
c6788ecf
BA
233 this.people.push({name:"", id:0, sid:data.from});
234 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
5f131484
BA
235 break;
236 }
237 case "disconnect":
c6788ecf 238 ArrayFun.remove(this.people, p => p.sid == data.from);
a6088c90
BA
239 break;
240 }
cdb34c93 241 },
760adbce
BA
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.$refs["basegame"].play(data.lastMove,
251 "receive", this.game.vname!="Dark" ? "animate" : null);
252 if (data.score != "*" && this.game.score == "*")
253 {
254 // Opponent resigned or aborted game, or accepted draw offer
255 // (this is not a stalemate or checkmate)
256 this.$refs["basegame"].endGame(data.score, "Opponent action");
257 }
258 this.game.clocks = data.clocks; //TODO: check this?
259 if (!!data.lastMove.draw)
260 this.drawOffer = "received";
261 }
262 },
a6088c90 263 offerDraw: function() {
6fba6e0c
BA
264 if (this.drawOffer == "received")
265 {
2cc10cdb 266 if (!confirm("Accept draw?"))
6fba6e0c 267 return;
760adbce
BA
268 this.people.forEach(p => {
269 if (p.sid != this.st.user.sid)
270 this.st.conn.send(JSON.stringify({code:"draw", target:p.sid}));
271 });
2cc10cdb
BA
272 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
273 }
6fba6e0c 274 else if (this.drawOffer == "sent")
b7cbbda1 275 {
6fba6e0c 276 this.drawOffer = "";
b7cbbda1
BA
277 if (this.game.type == "corr")
278 GameStorage.update(this.gameRef.id, {drawOffer: false});
279 }
6fba6e0c
BA
280 else
281 {
282 if (!confirm("Offer draw?"))
283 return;
760adbce
BA
284 this.drawOffer = "sent";
285 this.people.forEach(p => {
286 if (p.sid != this.st.user.sid)
287 this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid}));
288 });
b7cbbda1
BA
289 if (this.game.type == "corr")
290 GameStorage.update(this.gameRef.id, {drawOffer: true});
a6088c90
BA
291 }
292 },
7f3484bd
BA
293 abortGame: function() {
294 if (!confirm(this.st.tr["Terminate game?"]))
295 return;
296 // Next line will trigger a "gameover" event, bubbling up till here
297 this.$refs["basegame"].endGame("?", "Abort");
298 this.people.forEach(p => {
299 if (p.sid != this.st.user.sid)
5f131484
BA
300 {
301 this.st.conn.send(JSON.stringify({
302 code: "abort",
7f3484bd 303 target: p.sid,
5f131484
BA
304 }));
305 }
7f3484bd 306 });
a6088c90
BA
307 },
308 resign: function(e) {
309 if (!confirm("Resign the game?"))
310 return;
760adbce
BA
311 this.people.forEach(p => {
312 if (p.sid != this.st.user.sid)
313 {
314 this.st.conn.send(JSON.stringify({code:"resign",
315 side:this.game.mycolor, target:p.sid}));
316 }
317 });
93d1d7a7 318 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
319 this.$refs["basegame"].endGame(
320 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 321 },
967a2686
BA
322 // 3 cases for loading a game:
323 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
324 // - from server (one correspondance game I play[ed] or not)
325 // - from remote peer (one live game I don't play, finished or not)
760adbce 326 loadGame: function(game, callback) {
967a2686 327 const afterRetrieval = async (game) => {
f41ce580
BA
328 const vModule = await import("@/variants/" + game.vname + ".js");
329 window.V = vModule.VariantRules;
330 this.vr = new V(game.fen);
c0b27606 331 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
92a523d1 332 const tc = extractTime(game.timeControl);
c0b27606
BA
333 if (gtype == "corr")
334 {
f41ce580
BA
335 if (game.players[0].color == "b")
336 {
337 // Adopt the same convention for live and corr games: [0] = white
338 [ game.players[0], game.players[1] ] =
339 [ game.players[1], game.players[0] ];
340 }
c0b27606 341 // corr game: needs to compute the clocks + initime
7f3484bd 342 // NOTE: clocks in seconds, initime in milliseconds
92a523d1 343 game.clocks = [tc.mainTime, tc.mainTime];
92b82def 344 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
b7cbbda1 345 if (game.score == "*") //otherwise no need to bother with time
92a523d1 346 {
b7cbbda1
BA
347 game.initime = [0, 0];
348 const L = game.moves.length;
349 if (L >= 3)
5f131484 350 {
b7cbbda1
BA
351 let addTime = [0, 0];
352 for (let i=2; i<L; i++)
353 {
354 addTime[i%2] += tc.increment -
355 (game.moves[i].played - game.moves[i-1].played) / 1000;
356 }
357 for (let i=0; i<=1; i++)
358 game.clocks[i] += addTime[i];
5f131484 359 }
b7cbbda1
BA
360 if (L >= 1)
361 game.initime[L%2] = game.moves[L-1].played;
362 if (game.drawOffer)
363 this.drawOffer = "received";
92a523d1 364 }
92b82def 365 // Now that we used idx and played, re-format moves as for live games
6d68309a 366 game.moves = game.moves.map( (m) => {
92b82def 367 const s = m.squares;
6d68309a 368 return {
92b82def
BA
369 appear: s.appear,
370 vanish: s.vanish,
371 start: s.start,
372 end: s.end,
373 message: m.message,
374 };
375 });
c0b27606 376 }
f41ce580
BA
377 const myIdx = game.players.findIndex(p => {
378 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
379 });
92a523d1 380 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
66d03f23
BA
381 {
382 game.clocks = [tc.mainTime, tc.mainTime];
b7cbbda1 383 if (game.score == "*")
22efa391 384 {
b7cbbda1
BA
385 game.initime[0] = Date.now();
386 if (myIdx >= 0)
22efa391 387 {
b7cbbda1
BA
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 }
22efa391 395 }
66d03f23 396 }
4b0384fa
BA
397 this.game = Object.assign({},
398 game,
cf742aaf 399 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 400 {
c0b27606 401 type: gtype,
66d03f23 402 increment: tc.increment,
6fba6e0c 403 mycolor: [undefined,"w","b"][myIdx+1],
5f131484
BA
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),
6fba6e0c 408 }
4b0384fa 409 );
760adbce
BA
410 if (!!this.lastate) //lastate arrived before game was loaded:
411 this.processLastate();
412 callback();
967a2686
BA
413 };
414 if (!!game)
dc284d90 415 return afterRetrieval(game);
967a2686
BA
416 if (!!this.gameRef.rid)
417 {
760adbce 418 // Remote live game: forgetting about callback func... (TODO: design)
5f131484
BA
419 this.st.conn.send(JSON.stringify(
420 {code:"askfullgame", target:this.gameRef.rid}));
967a2686
BA
421 }
422 else
423 {
f41ce580 424 // Local or corr game
11667c79 425 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 426 }
a6088c90 427 },
9d54ab89 428 // Post-process a move (which was just played)
ce87ac6a 429 processMove: function(move) {
b4fb1612
BA
430 if (!this.game.mycolor)
431 return; //I'm just an observer
9d54ab89 432 // Update storage (corr or live)
6fba6e0c 433 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89
BA
434 // https://stackoverflow.com/a/38750895
435 const allowed_fields = ["appear", "vanish", "start", "end"];
436 const filtered_move = Object.keys(move)
437 .filter(key => allowed_fields.includes(key))
438 .reduce((obj, key) => {
8a7452b5 439 obj[key] = move[key];
9d54ab89
BA
440 return obj;
441 }, {});
dc284d90 442 // Send move ("newmove" event) to people in the room (if our turn)
dce792f6 443 let addTime = 0;
9d54ab89 444 if (move.color == this.game.mycolor)
b4fb1612 445 {
dce792f6
BA
446 if (this.game.moves.length >= 2) //after first move
447 {
448 const elapsed = Date.now() - this.game.initime[colorIdx];
449 // elapsed time is measured in milliseconds
450 addTime = this.game.increment - elapsed/1000;
451 }
6d68309a
BA
452 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
453 if (this.game.type == "corr")
454 sendMove.message = this.corrMsg;
dc284d90
BA
455 this.people.forEach(p => {
456 if (p.sid != this.st.user.sid)
457 {
458 this.st.conn.send(JSON.stringify({
459 code: "newmove",
460 target: p.sid,
461 move: sendMove,
462 }));
463 }
464 });
a4480041
BA
465 if (this.game.type == "corr" && this.corrMsg != "")
466 {
467 // Add message to last move in BaseGame:
468 // TODO: not very good style...
469 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
470 }
b4fb1612 471 }
5b87454c
BA
472 else
473 addTime = move.addTime; //supposed transmitted
6fba6e0c 474 const nextIdx = ["w","b"].indexOf(this.vr.turn);
6d68309a
BA
475 // Since corr games are stored at only one location, update should be
476 // done only by one player for each move:
477 if (this.game.type == "live" || move.color == this.game.mycolor)
967a2686 478 {
e69f159d 479 if (this.game.type == "corr")
f41ce580 480 {
e69f159d 481 GameStorage.update(this.gameRef.id,
6d68309a 482 {
e69f159d
BA
483 fen: move.fen,
484 move:
485 {
486 squares: filtered_move,
487 message: this.corrMsg,
488 played: Date.now(), //TODO: on server?
489 idx: this.game.moves.length,
490 },
491 });
492 }
493 else //live
494 {
495 GameStorage.update(this.gameRef.id,
496 {
497 fen: move.fen,
498 move: filtered_move,
499 clocks: this.game.clocks.map((t,i) => i==colorIdx
500 ? this.game.clocks[i] + addTime
501 : this.game.clocks[i]),
502 initime: this.game.initime.map((t,i) => i==nextIdx
503 ? Date.now()
504 : this.game.initime[i]),
505 });
506 }
6d68309a 507 }
967a2686
BA
508 // Also update current game object:
509 this.game.moves.push(move);
510 this.game.fen = move.fen;
760adbce 511 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
66d03f23 512 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
809ba2aa 513 this.game.initime[nextIdx] = Date.now();
6d68309a
BA
514 // Finally reset curMoveMessage if needed
515 if (this.game.type == "corr" && move.color == this.game.mycolor)
516 this.corrMsg = "";
b4fb1612
BA
517 },
518 gameOver: function(score) {
93d1d7a7 519 this.game.mode = "analyze";
d18bfa12 520 this.game.score = score;
ab6f48ea
BA
521 const myIdx = this.game.players.findIndex(p => {
522 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
523 });
524 if (myIdx >= 0) //OK, I play in this game
525 GameStorage.update(this.gameRef.id, { score: score });
ce87ac6a 526 },
a6088c90
BA
527 },
528};
529</script>
7e1a1fe9
BA
530
531<style lang="sass">
532// TODO
533</style>