Parameters adjustments + cosmetics
[vchess.git] / client / src / views / Game.vue
CommitLineData
a6088c90
BA
1<template lang="pug">
2.row
3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
b988c726
BA
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"] }}
b4fb1612
BA
12 BaseGame(:game="game" :vr="vr" ref="basegame"
13 @newmove="processMove" @gameover="gameOver")
f41ce580 14 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
809ba2aa 15 div Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
d4036efe 16 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
a6088c90 17 button(@click="offerDraw") Draw
b988c726 18 button(@click="() => abortGame()") Abort
a6088c90 19 button(@click="resign") Resign
9330b976 20 textarea(v-if="game.score=='*'" v-model="corrMsg")
a6088c90
BA
21</template>
22
9aa229f3
BA
23<!--
24// TODO: movelist dans basegame et chat ici
9aa229f3
BA
25// ==> après, implémenter/vérifier les passages de challenges + parties en cours
26// observer,
27// + problèmes, habiller et publier. (+ corr...)
6fba6e0c 28// when send to chat (or a move), reach only this group (send gid along)
9aa229f3
BA
29-->
30
a6088c90 31<script>
46284a2f 32import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
33//import Chat from "@/components/Chat.vue";
34//import MoveList from "@/components/MoveList.vue";
35import { store } from "@/store";
967a2686 36import { GameStorage } from "@/utils/gameStorage";
5b87454c 37import { ppt } from "@/utils/datetime";
66d03f23 38import { extractTime } from "@/utils/timeControl";
f41ce580 39import { ArrayFun } from "@/utils/array";
a6088c90
BA
40
41export default {
42 name: 'my-game',
43 components: {
44 BaseGame,
45 },
f7121527 46 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
47 data: function() {
48 return {
49 st: store.state,
4b0384fa
BA
50 gameRef: { //given in URL (rid = remote ID)
51 id: "",
52 rid: ""
53 },
f41ce580 54 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
6fba6e0c 55 corrMsg: "", //to send offline messages in corr games
809ba2aa 56 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 57 vr: null, //"variant rules" object initialized from FEN
6fba6e0c 58 drawOffer: "", //TODO: use for button style
92a523d1 59 people: [], //players + observers
a6088c90
BA
60 };
61 },
62 watch: {
5f131484
BA
63 "$route": function(to, from) {
64 this.gameRef.id = to.params["id"];
65 this.gameRef.rid = to.query["rid"];
66 this.loadGame();
a6088c90 67 },
5b87454c 68 "game.clocks": function(newState) {
dce792f6
BA
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 }
809ba2aa 75 const currentTurn = this.vr.turn;
6fba6e0c 76 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
77 let countdown = newState[colorIdx] -
78 (Date.now() - this.game.initime[colorIdx])/1000;
c0b27606
BA
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 });
809ba2aa 85 let clockUpdate = setInterval(() => {
e69f159d 86 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
809ba2aa
BA
87 {
88 clearInterval(clockUpdate);
e69f159d 89 if (countdown < 0)
809ba2aa
BA
90 {
91 this.$refs["basegame"].endGame(
e69f159d 92 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
809ba2aa
BA
93 }
94 }
9aa229f3
BA
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 }
809ba2aa 100 }, 1000);
5b87454c 101 },
92a523d1 102 },
5f131484 103 // TODO: redundant code with Hall.vue (related to people array)
a6088c90 104 created: function() {
5f131484
BA
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});
f7121527 108 if (!!this.$route.params["id"])
a6088c90 109 {
f7121527
BA
110 this.gameRef.id = this.$route.params["id"];
111 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 112 this.loadGame();
f7121527 113 }
5f131484
BA
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;
cdb34c93
BA
123 const socketCloseListener = () => {
124 store.socketCloseListener(); //reinitialize connexion (in store.js)
a9b131f1 125 this.st.conn.addEventListener('message', this.socketMessageListener);
cdb34c93
BA
126 this.st.conn.addEventListener('close', socketCloseListener);
127 };
cdb34c93
BA
128 this.st.conn.onclose = socketCloseListener;
129 },
130 methods: {
5f131484
BA
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 },
cdb34c93 137 socketMessageListener: function(msg) {
a6088c90 138 const data = JSON.parse(msg.data);
a6088c90
BA
139 switch (data.code)
140 {
5f131484
BA
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 {
f41ce580
BA
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)
411d23cd 169 {
f41ce580 170 // Send our "last state" informations to opponent
411d23cd
BA
171 const L = this.game.moves.length;
172 this.st.conn.send(JSON.stringify({
173 code: "lastate",
f41ce580
BA
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 }
411d23cd
BA
183 }));
184 }
a6088c90 185 break;
6fba6e0c 186 }
f41ce580
BA
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;
a6088c90 192 case "lastate": //got opponent infos about last move
6fba6e0c
BA
193 {
194 const L = this.game.moves.length;
6fba6e0c 195 if (data.movesCount > L)
a6088c90 196 {
6fba6e0c 197 // Just got last move from him
f41ce580
BA
198 this.$refs["basegame"].play(data.lastMove,
199 "receive", this.game.vname!="Dark" ? "animate" : null);
6fba6e0c
BA
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 }
f41ce580
BA
206 this.game.clocks = data.clocks; //TODO: check this?
207 this.drawOffer = data.drawOffer; //does opponent offer draw?
a6088c90 208 }
a6088c90 209 break;
6fba6e0c 210 }
93d1d7a7
BA
211 case "resign":
212 this.$refs["basegame"].endGame(
213 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
214 break;
93d1d7a7
BA
215 case "abort":
216 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
217 break;
2cc10cdb
BA
218 case "draw":
219 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
220 break;
221 case "drawoffer":
222 this.drawOffer = "received";
223 break;
7e1a1fe9
BA
224 case "askfullgame":
225 // TODO: just give game; observers are listed here anyway:
5f131484
BA
226 // ==> mark request SID as someone to send moves to
227 // NOT to all people array: our opponent can send moves too!
7e1a1fe9 228 break;
5f131484
BA
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 {
5f131484
BA
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);
a6088c90
BA
244 break;
245 }
cdb34c93 246 },
a6088c90 247 offerDraw: function() {
2cc10cdb 248 // TODO: also for corr games
6fba6e0c
BA
249 if (this.drawOffer == "received")
250 {
2cc10cdb 251 if (!confirm("Accept draw?"))
6fba6e0c 252 return;
5f131484
BA
253 const oppsid = this.getOppSid();
254 if (!!oppsid)
255 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
2cc10cdb
BA
256 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
257 }
6fba6e0c
BA
258 else if (this.drawOffer == "sent")
259 this.drawOffer = "";
260 else
261 {
262 if (!confirm("Offer draw?"))
263 return;
5f131484
BA
264 const oppsid = this.getOppSid();
265 if (!!oppsid)
266 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
a6088c90
BA
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 },
b988c726 275 abortGame: function(event) {
9aa229f3 276 let modalBox = document.getElementById("modalAbort");
b988c726
BA
277 if (!event)
278 {
279 // First call show options:
b988c726
BA
280 modalBox.checked = true;
281 }
282 else
283 {
9aa229f3
BA
284 modalBox.checked = false; //decision made: box disappear
285 const message = event.target.innerText;
d4036efe 286 // Next line will trigger a "gameover" event, bubbling up till here
9aa229f3 287 this.$refs["basegame"].endGame("?", "Abort: " + message);
5f131484
BA
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 }
b988c726 297 }
a6088c90
BA
298 },
299 resign: function(e) {
300 if (!confirm("Resign the game?"))
301 return;
5f131484
BA
302 const oppsid = this.getOppSid();
303 if (!!oppsid)
304 {
305 this.st.conn.send(JSON.stringify({
306 code: "resign",
307 target: oppsid,
308 }));
309 }
93d1d7a7 310 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
311 this.$refs["basegame"].endGame(
312 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 313 },
967a2686
BA
314 // 3 cases for loading a game:
315 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
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)
967a2686
BA
318 loadGame: function(game) {
319 const afterRetrieval = async (game) => {
f41ce580
BA
320 const vModule = await import("@/variants/" + game.vname + ".js");
321 window.V = vModule.VariantRules;
322 this.vr = new V(game.fen);
c0b27606 323 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
92a523d1 324 const tc = extractTime(game.timeControl);
c0b27606
BA
325 if (gtype == "corr")
326 {
f41ce580
BA
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 }
c0b27606 333 // corr game: needs to compute the clocks + initime
92a523d1 334 game.clocks = [tc.mainTime, tc.mainTime];
c0b27606 335 game.initime = [0, 0];
5f131484 336 const L = game.moves.length;
92b82def 337 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
5f131484 338 if (L >= 3)
92a523d1 339 {
5f131484
BA
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];
92a523d1 348 }
5f131484
BA
349 if (L >= 1)
350 game.initime[L%2] = game.moves[L-1].played;
92b82def 351 // Now that we used idx and played, re-format moves as for live games
6d68309a 352 game.moves = game.moves.map( (m) => {
92b82def 353 const s = m.squares;
6d68309a 354 return {
92b82def
BA
355 appear: s.appear,
356 vanish: s.vanish,
357 start: s.start,
358 end: s.end,
359 message: m.message,
360 };
361 });
c0b27606 362 }
f41ce580
BA
363 const myIdx = game.players.findIndex(p => {
364 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
365 });
92a523d1 366 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
66d03f23
BA
367 {
368 game.clocks = [tc.mainTime, tc.mainTime];
369 game.initime[0] = Date.now();
92a523d1 370 if (myIdx >= 0)
22efa391 371 {
cf742aaf 372 // I play in this live game; corr games don't have clocks+initime
d18bfa12 373 GameStorage.update(game.id,
22efa391
BA
374 {
375 clocks: game.clocks,
376 initime: game.initime,
377 });
378 }
66d03f23 379 }
4b0384fa
BA
380 this.game = Object.assign({},
381 game,
cf742aaf 382 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 383 {
c0b27606 384 type: gtype,
66d03f23 385 increment: tc.increment,
6fba6e0c 386 mycolor: [undefined,"w","b"][myIdx+1],
5f131484
BA
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),
6fba6e0c 391 }
4b0384fa 392 );
967a2686
BA
393 };
394 if (!!game)
395 return afterRetrival(game);
396 if (!!this.gameRef.rid)
397 {
f41ce580 398 // Remote live game
5f131484
BA
399 this.st.conn.send(JSON.stringify(
400 {code:"askfullgame", target:this.gameRef.rid}));
967a2686 401 // (send moves updates + resign/abort/draw actions)
967a2686
BA
402 }
403 else
404 {
f41ce580 405 // Local or corr game
11667c79 406 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 407 }
a6088c90 408 },
9d54ab89 409 // Post-process a move (which was just played)
ce87ac6a 410 processMove: function(move) {
b4fb1612
BA
411 if (!this.game.mycolor)
412 return; //I'm just an observer
9d54ab89 413 // Update storage (corr or live)
6fba6e0c 414 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89
BA
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) => {
8a7452b5 420 obj[key] = move[key];
9d54ab89
BA
421 return obj;
422 }, {});
b4fb1612 423 // Send move ("newmove" event) to opponent(s) (if ours)
dce792f6 424 let addTime = 0;
9d54ab89 425 if (move.color == this.game.mycolor)
b4fb1612 426 {
dce792f6
BA
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 }
6d68309a
BA
433 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
434 if (this.game.type == "corr")
435 sendMove.message = this.corrMsg;
a4480041
BA
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 }
b4fb1612 451 }
5b87454c
BA
452 else
453 addTime = move.addTime; //supposed transmitted
6fba6e0c 454 const nextIdx = ["w","b"].indexOf(this.vr.turn);
6d68309a
BA
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)
967a2686 458 {
e69f159d 459 if (this.game.type == "corr")
f41ce580 460 {
e69f159d 461 GameStorage.update(this.gameRef.id,
6d68309a 462 {
e69f159d
BA
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 }
6d68309a 487 }
967a2686
BA
488 // Also update current game object:
489 this.game.moves.push(move);
490 this.game.fen = move.fen;
66d03f23
BA
491 //TODO: just this.game.clocks[colorIdx] += addTime;
492 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
809ba2aa 493 this.game.initime[nextIdx] = Date.now();
6d68309a
BA
494 // Finally reset curMoveMessage if needed
495 if (this.game.type == "corr" && move.color == this.game.mycolor)
496 this.corrMsg = "";
b4fb1612
BA
497 },
498 gameOver: function(score) {
93d1d7a7 499 this.game.mode = "analyze";
d18bfa12 500 this.game.score = score;
22efa391 501 GameStorage.update(this.gameRef.id, { score: score });
ce87ac6a 502 },
a6088c90
BA
503 },
504};
505</script>
7e1a1fe9
BA
506
507<style lang="sass">
508// TODO
509</style>