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