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