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