e417e5e434506fb7adf826616edc9b4d0b5e772f
[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 textarea#mvMessage(v-if="game.type=='corr'" v-model="corrMsg")
15 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
16 div Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
17 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
18 button(@click="offerDraw") Draw
19 button(@click="() => abortGame()") Abort
20 button(@click="resign") Resign
21 div(v-if="game.type=='corr'")
22 textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
23 div(v-show="cursor>=0") {{ moves[cursor].message }}
24 </template>
25
26 <!--
27 // TODO: movelist dans basegame et chat ici
28 // ==> après, implémenter/vérifier les passages de challenges + parties en cours
29 // observer,
30 // + problèmes, habiller et publier. (+ corr...)
31 // when send to chat (or a move), reach only this group (send gid along)
32 -->
33
34 <script>
35 import BaseGame from "@/components/BaseGame.vue";
36 //import Chat from "@/components/Chat.vue";
37 //import MoveList from "@/components/MoveList.vue";
38 import { store } from "@/store";
39 import { GameStorage } from "@/utils/gameStorage";
40 import { ppt } from "@/utils/datetime";
41 import { extractTime } from "@/utils/timeControl";
42 import { ArrayFun } from "@/utils/array";
43
44 export default {
45 name: 'my-game',
46 components: {
47 BaseGame,
48 },
49 // gameRef: to find the game in (potentially remote) storage
50 data: function() {
51 return {
52 st: store.state,
53 gameRef: { //given in URL (rid = remote ID)
54 id: "",
55 rid: ""
56 },
57 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
58 corrMsg: "", //to send offline messages in corr games
59 virtualClocks: [0, 0], //initialized with true game.clocks
60 vr: null, //"variant rules" object initialized from FEN
61 drawOffer: "", //TODO: use for button style
62 people: [], //players + observers
63 };
64 },
65 watch: {
66 "$route": function(to, from) {
67 this.gameRef.id = to.params["id"];
68 this.gameRef.rid = to.query["rid"];
69 this.loadGame();
70 },
71 "game.clocks": function(newState) {
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 }
78 const currentTurn = this.vr.turn;
79 const colorIdx = ["w","b"].indexOf(currentTurn);
80 let countdown = newState[colorIdx] -
81 (Date.now() - this.game.initime[colorIdx])/1000;
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 });
88 let clockUpdate = setInterval(() => {
89 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
90 {
91 clearInterval(clockUpdate);
92 if (countdown < 0)
93 {
94 this.$refs["basegame"].endGame(
95 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
96 }
97 }
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 }
103 }, 1000);
104 },
105 },
106 // TODO: redundant code with Hall.vue (related to people array)
107 created: function() {
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});
111 if (!!this.$route.params["id"])
112 {
113 this.gameRef.id = this.$route.params["id"];
114 this.gameRef.rid = this.$route.query["rid"];
115 this.loadGame();
116 }
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;
126 const socketCloseListener = () => {
127 store.socketCloseListener(); //reinitialize connexion (in store.js)
128 this.st.conn.addEventListener('message', this.socketMessageListener);
129 this.st.conn.addEventListener('close', socketCloseListener);
130 };
131 this.st.conn.onclose = socketCloseListener;
132 },
133 methods: {
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 },
140 socketMessageListener: function(msg) {
141 const data = JSON.parse(msg.data);
142 switch (data.code)
143 {
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 {
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)
172 {
173 // Send our "last state" informations to opponent
174 const L = this.game.moves.length;
175 this.st.conn.send(JSON.stringify({
176 code: "lastate",
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 }
186 }));
187 }
188 break;
189 }
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;
195 case "lastate": //got opponent infos about last move
196 {
197 const L = this.game.moves.length;
198 if (data.movesCount > L)
199 {
200 // Just got last move from him
201 this.$refs["basegame"].play(data.lastMove,
202 "receive", this.game.vname!="Dark" ? "animate" : null);
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 }
209 this.game.clocks = data.clocks; //TODO: check this?
210 this.drawOffer = data.drawOffer; //does opponent offer draw?
211 }
212 break;
213 }
214 case "resign":
215 this.$refs["basegame"].endGame(
216 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
217 break;
218 case "abort":
219 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
220 break;
221 case "draw":
222 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
223 break;
224 case "drawoffer":
225 this.drawOffer = "received";
226 break;
227 case "askfullgame":
228 // TODO: just give game; observers are listed here anyway:
229 // ==> mark request SID as someone to send moves to
230 // NOT to all people array: our opponent can send moves too!
231 break;
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 {
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);
247 break;
248 }
249 },
250 offerDraw: function() {
251 // TODO: also for corr games
252 if (this.drawOffer == "received")
253 {
254 if (!confirm("Accept draw?"))
255 return;
256 const oppsid = this.getOppSid();
257 if (!!oppsid)
258 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
259 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
260 }
261 else if (this.drawOffer == "sent")
262 this.drawOffer = "";
263 else
264 {
265 if (!confirm("Offer draw?"))
266 return;
267 const oppsid = this.getOppSid();
268 if (!!oppsid)
269 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
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 },
278 abortGame: function(event) {
279 let modalBox = document.getElementById("modalAbort");
280 if (!event)
281 {
282 // First call show options:
283 modalBox.checked = true;
284 }
285 else
286 {
287 modalBox.checked = false; //decision made: box disappear
288 const message = event.target.innerText;
289 // Next line will trigger a "gameover" event, bubbling up till here
290 this.$refs["basegame"].endGame("?", "Abort: " + message);
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 }
300 }
301 },
302 resign: function(e) {
303 if (!confirm("Resign the game?"))
304 return;
305 const oppsid = this.getOppSid();
306 if (!!oppsid)
307 {
308 this.st.conn.send(JSON.stringify({
309 code: "resign",
310 target: oppsid,
311 }));
312 }
313 // Next line will trigger a "gameover" event, bubbling up till here
314 this.$refs["basegame"].endGame(
315 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
316 },
317 // 3 cases for loading a game:
318 // - from indexedDB (running or completed live game I play)
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)
321 loadGame: function(game) {
322 const afterRetrieval = async (game) => {
323 const vModule = await import("@/variants/" + game.vname + ".js");
324 window.V = vModule.VariantRules;
325 this.vr = new V(game.fen);
326 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
327 const tc = extractTime(game.timeControl);
328 if (gtype == "corr")
329 {
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 }
336 // corr game: needs to compute the clocks + initime
337 game.clocks = [tc.mainTime, tc.mainTime];
338 game.initime = [0, 0];
339 const L = game.moves.length;
340 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
341 if (L >= 3)
342 {
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];
351 }
352 if (L >= 1)
353 game.initime[L%2] = game.moves[L-1].played;
354 // Now that we used idx and played, re-format moves as for live games
355 game.moves = game.moves.map( (m) => {
356 const s = m.squares;
357 return {
358 appear: s.appear,
359 vanish: s.vanish,
360 start: s.start,
361 end: s.end,
362 message: m.message,
363 };
364 });
365 }
366 const myIdx = game.players.findIndex(p => {
367 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
368 });
369 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
370 {
371 game.clocks = [tc.mainTime, tc.mainTime];
372 game.initime[0] = Date.now();
373 if (myIdx >= 0)
374 {
375 // I play in this live game; corr games don't have clocks+initime
376 GameStorage.update(game.id,
377 {
378 clocks: game.clocks,
379 initime: game.initime,
380 });
381 }
382 }
383 this.game = Object.assign({},
384 game,
385 // NOTE: assign mycolor here, since BaseGame could also be VS computer
386 {
387 type: gtype,
388 increment: tc.increment,
389 mycolor: [undefined,"w","b"][myIdx+1],
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),
394 }
395 );
396 };
397 if (!!game)
398 return afterRetrival(game);
399 if (!!this.gameRef.rid)
400 {
401 // Remote live game
402 this.st.conn.send(JSON.stringify(
403 {code:"askfullgame", target:this.gameRef.rid}));
404 // (send moves updates + resign/abort/draw actions)
405 }
406 else
407 {
408 // Local or corr game
409 GameStorage.get(this.gameRef.id, afterRetrieval);
410 }
411 },
412 // Post-process a move (which was just played)
413 processMove: function(move) {
414 if (!this.game.mycolor)
415 return; //I'm just an observer
416 // Update storage (corr or live)
417 const colorIdx = ["w","b"].indexOf(move.color);
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) => {
423 obj[key] = move[key];
424 return obj;
425 }, {});
426 // Send move ("newmove" event) to opponent(s) (if ours)
427 let addTime = 0;
428 if (move.color == this.game.mycolor)
429 {
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 }
436 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
437 if (this.game.type == "corr")
438 sendMove.message = this.corrMsg;
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 }
454 }
455 else
456 addTime = move.addTime; //supposed transmitted
457 const nextIdx = ["w","b"].indexOf(this.vr.turn);
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)
461 {
462 if (this.game.type == "corr")
463 {
464 GameStorage.update(this.gameRef.id,
465 {
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 }
490 }
491 // Also update current game object:
492 this.game.moves.push(move);
493 this.game.fen = move.fen;
494 //TODO: just this.game.clocks[colorIdx] += addTime;
495 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
496 this.game.initime[nextIdx] = Date.now();
497 // Finally reset curMoveMessage if needed
498 if (this.game.type == "corr" && move.color == this.game.mycolor)
499 this.corrMsg = "";
500 },
501 gameOver: function(score) {
502 this.game.mode = "analyze";
503 this.game.score = score;
504 GameStorage.update(this.gameRef.id, { score: score });
505 },
506 },
507 };
508 </script>
509
510 <style lang="sass">
511 // TODO
512 </style>