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