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