Rename gameId --> id in Game.vue
[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")
6d68309a 14 textarea#mvMessage(v-if="game.type=='corr'" v-model="corrMsg")
f41ce580 15 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
809ba2aa 16 div Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
d4036efe 17 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
a6088c90 18 button(@click="offerDraw") Draw
b988c726 19 button(@click="() => abortGame()") Abort
a6088c90 20 button(@click="resign") Resign
6dd02928 21 div(v-if="game.mode=='corr'")
4b0384fa 22 textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
a6088c90
BA
23 div(v-show="cursor>=0") {{ moves[cursor].message }}
24</template>
25
9aa229f3
BA
26<!--
27// TODO: movelist dans basegame et chat ici
9aa229f3
BA
28// ==> après, implémenter/vérifier les passages de challenges + parties en cours
29// observer,
30// + problèmes, habiller et publier. (+ corr...)
6fba6e0c 31// when send to chat (or a move), reach only this group (send gid along)
9aa229f3
BA
32-->
33
a6088c90 34<script>
46284a2f 35import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
36//import Chat from "@/components/Chat.vue";
37//import MoveList from "@/components/MoveList.vue";
38import { store } from "@/store";
967a2686 39import { GameStorage } from "@/utils/gameStorage";
5b87454c 40import { ppt } from "@/utils/datetime";
66d03f23 41import { extractTime } from "@/utils/timeControl";
f41ce580 42import { ArrayFun } from "@/utils/array";
a6088c90
BA
43
44export default {
45 name: 'my-game',
46 components: {
47 BaseGame,
48 },
f7121527 49 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
50 data: function() {
51 return {
52 st: store.state,
4b0384fa
BA
53 gameRef: { //given in URL (rid = remote ID)
54 id: "",
55 rid: ""
56 },
f41ce580 57 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
6fba6e0c 58 corrMsg: "", //to send offline messages in corr games
809ba2aa 59 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 60 vr: null, //"variant rules" object initialized from FEN
6fba6e0c 61 drawOffer: "", //TODO: use for button style
92a523d1 62 people: [], //players + observers
a6088c90
BA
63 };
64 },
65 watch: {
5f131484
BA
66 "$route": function(to, from) {
67 this.gameRef.id = to.params["id"];
68 this.gameRef.rid = to.query["rid"];
69 this.loadGame();
a6088c90 70 },
5b87454c 71 "game.clocks": function(newState) {
dce792f6
BA
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 }
809ba2aa 78 const currentTurn = this.vr.turn;
6fba6e0c 79 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
80 let countdown = newState[colorIdx] -
81 (Date.now() - this.game.initime[colorIdx])/1000;
c0b27606
BA
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 });
809ba2aa 88 const myTurn = (currentTurn == this.game.mycolor);
809ba2aa 89 let clockUpdate = setInterval(() => {
d18bfa12 90 if (countdown <= 0 || this.vr.turn != currentTurn || this.game.score != "*")
809ba2aa
BA
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");
5f131484
BA
97 const oppsid = this.getOppSid();
98 if (!!oppsid)
99 {
100 this.st.conn.send(JSON.stringify({
101 code: "timeover",
102 target: oppsid,
103 }));
104 }
809ba2aa
BA
105 }
106 }
9aa229f3
BA
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 }
809ba2aa 112 }, 1000);
5b87454c 113 },
92a523d1 114 },
5f131484 115 // TODO: redundant code with Hall.vue (related to people array)
a6088c90 116 created: function() {
5f131484
BA
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});
f7121527 120 if (!!this.$route.params["id"])
a6088c90 121 {
f7121527
BA
122 this.gameRef.id = this.$route.params["id"];
123 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 124 this.loadGame();
f7121527 125 }
5f131484
BA
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;
cdb34c93
BA
135 const socketCloseListener = () => {
136 store.socketCloseListener(); //reinitialize connexion (in store.js)
a9b131f1 137 this.st.conn.addEventListener('message', this.socketMessageListener);
cdb34c93
BA
138 this.st.conn.addEventListener('close', socketCloseListener);
139 };
cdb34c93
BA
140 this.st.conn.onclose = socketCloseListener;
141 },
142 methods: {
5f131484
BA
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 },
cdb34c93 149 socketMessageListener: function(msg) {
a6088c90 150 const data = JSON.parse(msg.data);
a6088c90
BA
151 switch (data.code)
152 {
5f131484
BA
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 {
f41ce580
BA
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)
411d23cd 181 {
f41ce580 182 // Send our "last state" informations to opponent
411d23cd
BA
183 const L = this.game.moves.length;
184 this.st.conn.send(JSON.stringify({
185 code: "lastate",
f41ce580
BA
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 }
411d23cd
BA
195 }));
196 }
a6088c90 197 break;
6fba6e0c 198 }
f41ce580
BA
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;
a6088c90 204 case "lastate": //got opponent infos about last move
6fba6e0c
BA
205 {
206 const L = this.game.moves.length;
6fba6e0c 207 if (data.movesCount > L)
a6088c90 208 {
6fba6e0c 209 // Just got last move from him
f41ce580
BA
210 this.$refs["basegame"].play(data.lastMove,
211 "receive", this.game.vname!="Dark" ? "animate" : null);
6fba6e0c
BA
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 }
f41ce580
BA
218 this.game.clocks = data.clocks; //TODO: check this?
219 this.drawOffer = data.drawOffer; //does opponent offer draw?
a6088c90 220 }
a6088c90 221 break;
6fba6e0c 222 }
93d1d7a7
BA
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");
a6088c90 230 break;
93d1d7a7
BA
231 case "abort":
232 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
233 break;
2cc10cdb
BA
234 case "draw":
235 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
236 break;
237 case "drawoffer":
238 this.drawOffer = "received";
239 break;
7e1a1fe9
BA
240 case "askfullgame":
241 // TODO: just give game; observers are listed here anyway:
5f131484
BA
242 // ==> mark request SID as someone to send moves to
243 // NOT to all people array: our opponent can send moves too!
7e1a1fe9 244 break;
5f131484
BA
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 {
5f131484
BA
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);
a6088c90
BA
260 break;
261 }
cdb34c93 262 },
a6088c90 263 offerDraw: function() {
2cc10cdb 264 // TODO: also for corr games
6fba6e0c
BA
265 if (this.drawOffer == "received")
266 {
2cc10cdb 267 if (!confirm("Accept draw?"))
6fba6e0c 268 return;
5f131484
BA
269 const oppsid = this.getOppSid();
270 if (!!oppsid)
271 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
2cc10cdb
BA
272 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
273 }
6fba6e0c
BA
274 else if (this.drawOffer == "sent")
275 this.drawOffer = "";
276 else
277 {
278 if (!confirm("Offer draw?"))
279 return;
5f131484
BA
280 const oppsid = this.getOppSid();
281 if (!!oppsid)
282 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
a6088c90
BA
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 },
b988c726 291 abortGame: function(event) {
9aa229f3 292 let modalBox = document.getElementById("modalAbort");
b988c726
BA
293 if (!event)
294 {
295 // First call show options:
b988c726
BA
296 modalBox.checked = true;
297 }
298 else
299 {
9aa229f3
BA
300 modalBox.checked = false; //decision made: box disappear
301 const message = event.target.innerText;
d4036efe 302 // Next line will trigger a "gameover" event, bubbling up till here
9aa229f3 303 this.$refs["basegame"].endGame("?", "Abort: " + message);
5f131484
BA
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 }
b988c726 313 }
a6088c90
BA
314 },
315 resign: function(e) {
316 if (!confirm("Resign the game?"))
317 return;
5f131484
BA
318 const oppsid = this.getOppSid();
319 if (!!oppsid)
320 {
321 this.st.conn.send(JSON.stringify({
322 code: "resign",
323 target: oppsid,
324 }));
325 }
93d1d7a7 326 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
327 this.$refs["basegame"].endGame(
328 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 329 },
967a2686
BA
330 // 3 cases for loading a game:
331 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
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)
967a2686
BA
334 loadGame: function(game) {
335 const afterRetrieval = async (game) => {
f41ce580
BA
336 const vModule = await import("@/variants/" + game.vname + ".js");
337 window.V = vModule.VariantRules;
338 this.vr = new V(game.fen);
c0b27606 339 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
92a523d1 340 const tc = extractTime(game.timeControl);
c0b27606
BA
341 if (gtype == "corr")
342 {
f41ce580
BA
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 }
c0b27606 349 // corr game: needs to compute the clocks + initime
92a523d1 350 game.clocks = [tc.mainTime, tc.mainTime];
c0b27606 351 game.initime = [0, 0];
5f131484 352 const L = game.moves.length;
92b82def 353 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
5f131484 354 if (L >= 3)
92a523d1 355 {
5f131484
BA
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];
92a523d1 364 }
5f131484
BA
365 if (L >= 1)
366 game.initime[L%2] = game.moves[L-1].played;
92b82def 367 // Now that we used idx and played, re-format moves as for live games
6d68309a 368 game.moves = game.moves.map( (m) => {
92b82def 369 const s = m.squares;
6d68309a 370 return {
92b82def
BA
371 appear: s.appear,
372 vanish: s.vanish,
373 start: s.start,
374 end: s.end,
375 message: m.message,
376 };
377 });
c0b27606 378 }
f41ce580
BA
379 const myIdx = game.players.findIndex(p => {
380 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
381 });
92a523d1 382 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
66d03f23
BA
383 {
384 game.clocks = [tc.mainTime, tc.mainTime];
385 game.initime[0] = Date.now();
92a523d1 386 if (myIdx >= 0)
22efa391 387 {
cf742aaf 388 // I play in this live game; corr games don't have clocks+initime
d18bfa12 389 GameStorage.update(game.id,
22efa391
BA
390 {
391 clocks: game.clocks,
392 initime: game.initime,
393 });
394 }
66d03f23 395 }
4b0384fa
BA
396 this.game = Object.assign({},
397 game,
cf742aaf 398 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 399 {
c0b27606 400 type: gtype,
66d03f23 401 increment: tc.increment,
6fba6e0c 402 mycolor: [undefined,"w","b"][myIdx+1],
5f131484
BA
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),
6fba6e0c 407 }
4b0384fa 408 );
967a2686
BA
409 };
410 if (!!game)
411 return afterRetrival(game);
412 if (!!this.gameRef.rid)
413 {
f41ce580 414 // Remote live game
5f131484
BA
415 this.st.conn.send(JSON.stringify(
416 {code:"askfullgame", target:this.gameRef.rid}));
967a2686 417 // (send moves updates + resign/abort/draw actions)
967a2686
BA
418 }
419 else
420 {
f41ce580 421 // Local or corr game
11667c79 422 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 423 }
a6088c90 424 },
9d54ab89 425 // Post-process a move (which was just played)
ce87ac6a 426 processMove: function(move) {
b4fb1612
BA
427 if (!this.game.mycolor)
428 return; //I'm just an observer
9d54ab89 429 // Update storage (corr or live)
6fba6e0c 430 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89
BA
431 // https://stackoverflow.com/a/38750895
432 const allowed_fields = ["appear", "vanish", "start", "end"];
433 const filtered_move = Object.keys(move)
434 .filter(key => allowed_fields.includes(key))
435 .reduce((obj, key) => {
8a7452b5 436 obj[key] = move[key];
9d54ab89
BA
437 return obj;
438 }, {});
b4fb1612 439 // Send move ("newmove" event) to opponent(s) (if ours)
dce792f6 440 let addTime = 0;
9d54ab89 441 if (move.color == this.game.mycolor)
b4fb1612 442 {
dce792f6
BA
443 if (this.game.moves.length >= 2) //after first move
444 {
445 const elapsed = Date.now() - this.game.initime[colorIdx];
446 // elapsed time is measured in milliseconds
447 addTime = this.game.increment - elapsed/1000;
448 }
6d68309a
BA
449 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
450 if (this.game.type == "corr")
451 sendMove.message = this.corrMsg;
a4480041
BA
452 const oppsid = this.getOppSid();
453 if (!!oppsid)
454 {
455 this.st.conn.send(JSON.stringify({
456 code: "newmove",
457 target: oppsid,
458 move: sendMove,
459 }));
460 }
461 if (this.game.type == "corr" && this.corrMsg != "")
462 {
463 // Add message to last move in BaseGame:
464 // TODO: not very good style...
465 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
466 }
b4fb1612 467 }
5b87454c
BA
468 else
469 addTime = move.addTime; //supposed transmitted
6fba6e0c 470 const nextIdx = ["w","b"].indexOf(this.vr.turn);
6d68309a
BA
471 // Since corr games are stored at only one location, update should be
472 // done only by one player for each move:
473 if (this.game.type == "live" || move.color == this.game.mycolor)
967a2686 474 {
6d68309a 475 GameStorage.update(this.gameRef.id,
f41ce580 476 {
6d68309a
BA
477 fen: move.fen,
478 move:
479 {
480 squares: filtered_move,
481 message: this.corrMsg,
482 played: Date.now(), //TODO: on server?
483 idx: this.game.moves.length,
484 },
485 clocks: this.game.clocks.map((t,i) => i==colorIdx
486 ? this.game.clocks[i] + addTime
487 : this.game.clocks[i]),
488 initime: this.game.initime.map((t,i) => i==nextIdx
489 ? Date.now()
490 : this.game.initime[i]),
491 });
492 }
967a2686
BA
493 // Also update current game object:
494 this.game.moves.push(move);
495 this.game.fen = move.fen;
66d03f23
BA
496 //TODO: just this.game.clocks[colorIdx] += addTime;
497 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
809ba2aa 498 this.game.initime[nextIdx] = Date.now();
6d68309a
BA
499 // Finally reset curMoveMessage if needed
500 if (this.game.type == "corr" && move.color == this.game.mycolor)
501 this.corrMsg = "";
b4fb1612
BA
502 },
503 gameOver: function(score) {
93d1d7a7 504 this.game.mode = "analyze";
d18bfa12 505 this.game.score = score;
22efa391 506 GameStorage.update(this.gameRef.id, { score: score });
ce87ac6a 507 },
a6088c90
BA
508 },
509};
510</script>
7e1a1fe9
BA
511
512<style lang="sass">
513// TODO
514</style>