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