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