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