Small fix
[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")
6fba6e0c 14 // TODO: also show players names
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
BA
30 // TODO: how to know who is observing ? Send message to everyone with game ID ?
31 // and then just listen to (dis)connect events
32 // server always send "connect on " + URL ; then add to observers if game...
33// router when access a game page tell to server I joined + game ID (no need rid)
34// and ask server for current joined (= observers)
35// when send to chat (or a move), reach only this group (send gid along)
36// -> doivent être enregistrés comme observers au niveau du serveur...
37 // non: poll users + events startObserving / stopObserving
38 // (à faire au niveau du routeur ?)
9aa229f3
BA
39-->
40
a6088c90 41<script>
46284a2f 42import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
43//import Chat from "@/components/Chat.vue";
44//import MoveList from "@/components/MoveList.vue";
45import { store } from "@/store";
967a2686 46import { GameStorage } from "@/utils/gameStorage";
5b87454c 47import { ppt } from "@/utils/datetime";
66d03f23 48import { extractTime } from "@/utils/timeControl";
a6088c90
BA
49
50export default {
51 name: 'my-game',
52 components: {
53 BaseGame,
54 },
f7121527 55 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
56 data: function() {
57 return {
58 st: store.state,
4b0384fa
BA
59 gameRef: { //given in URL (rid = remote ID)
60 id: "",
61 rid: ""
62 },
63 game: { }, //passed to BaseGame
411d23cd 64 oppConnected: false, //TODO: use for styling
6fba6e0c 65 corrMsg: "", //to send offline messages in corr games
809ba2aa 66 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 67 vr: null, //"variant rules" object initialized from FEN
6fba6e0c 68 drawOffer: "", //TODO: use for button style
4b0384fa 69 people: [ ], //potential observers (TODO)
a6088c90
BA
70 };
71 },
72 watch: {
f7121527 73 '$route' (to, from) {
4fe5664d
BA
74 if (!!to.params["id"])
75 {
76 this.gameRef.id = to.params["id"];
77 this.gameRef.rid = to.query["rid"];
78 this.loadGame();
79 }
a6088c90 80 },
5b87454c 81 "game.clocks": function(newState) {
dce792f6
BA
82 if (this.game.moves.length < 2)
83 {
84 // 1st move not completed yet: freeze time
85 this.virtualClocks = newState.map(s => ppt(s));
86 return;
87 }
809ba2aa 88 const currentTurn = this.vr.turn;
6fba6e0c 89 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
90 let countdown = newState[colorIdx] -
91 (Date.now() - this.game.initime[colorIdx])/1000;
c0b27606
BA
92 this.virtualClocks = [0,1].map(i => {
93 const removeTime = i == colorIdx
94 ? (Date.now() - this.game.initime[colorIdx])/1000
95 : 0;
96 return ppt(newState[i] - removeTime);
97 });
809ba2aa 98 const myTurn = (currentTurn == this.game.mycolor);
809ba2aa 99 let clockUpdate = setInterval(() => {
d18bfa12 100 if (countdown <= 0 || this.vr.turn != currentTurn || this.game.score != "*")
809ba2aa
BA
101 {
102 clearInterval(clockUpdate);
103 if (countdown <= 0 && myTurn)
104 {
105 this.$refs["basegame"].endGame(
106 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
6fba6e0c
BA
107 this.st.conn.send(JSON.stringify({
108 code: "timeover",
109 target: this.game.oppid,
110 }));
809ba2aa
BA
111 }
112 }
9aa229f3
BA
113 else
114 {
115 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
116 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
117 }
809ba2aa 118 }, 1000);
5b87454c 119 },
fd7aea36
BA
120 // In case variants array was't loaded when game was retrieved
121 "st.variants": function(variantArray) {
122 if (!!this.game.vname && this.game.vname == "")
123 this.game.vname = variantArray.filter(v => v.id == this.game.vid)[0].name;
124 },
a6088c90 125 },
a6088c90 126 created: function() {
f7121527 127 if (!!this.$route.params["id"])
a6088c90 128 {
f7121527
BA
129 this.gameRef.id = this.$route.params["id"];
130 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 131 this.loadGame();
f7121527 132 }
cdb34c93
BA
133 // TODO: onopen, ask lastState informations + update observers and players status
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 };
139 this.st.conn.onmessage = this.socketMessageListener;
140 this.st.conn.onclose = socketCloseListener;
141 },
142 methods: {
143 socketMessageListener: function(msg) {
a6088c90 144 const data = JSON.parse(msg.data);
a6088c90
BA
145 switch (data.code)
146 {
f7121527 147 case "newmove":
c4f91d3f
BA
148 // NOTE: next call will trigger processMove()
149 this.$refs["basegame"].play(data.move,
150 "receive", this.game.vname!="Dark" ? "animate" : null);
a6088c90
BA
151 break;
152 case "pong": //received if we sent a ping (game still alive on our side)
6fba6e0c 153 {
a6088c90 154 this.oppConnected = true;
411d23cd
BA
155 if (this.game.type == "live") //corr games are always complete
156 {
157 // Send our "last state" informations to opponent(s)
158 const L = this.game.moves.length;
159 this.st.conn.send(JSON.stringify({
160 code: "lastate",
161 target: this.game.oppid,
162 gameId: this.gameRef.id,
163 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
164 score: this.game.score,
165 movesCount: L,
166 drawOffer: this.drawOffer,
167 clocks: this.game.clocks,
168 }));
169 }
a6088c90 170 break;
6fba6e0c 171 }
a6088c90 172 case "lastate": //got opponent infos about last move
6fba6e0c
BA
173 {
174 const L = this.game.moves.length;
a6088c90
BA
175 if (this.gameRef.id != data.gameId)
176 break; //games IDs don't match: nothing we can do...
177 // OK, opponent still in game (which might be over)
6fba6e0c 178 if (data.movesCount > L)
a6088c90 179 {
6fba6e0c
BA
180 // Just got last move from him
181 this.$refs["basegame"].play(data.lastMove, "receive");
182 if (data.score != "*" && this.game.score == "*")
183 {
184 // Opponent resigned or aborted game, or accepted draw offer
185 // (this is not a stalemate or checkmate)
186 this.$refs["basegame"].endGame(data.score, "Opponent action");
187 }
188 this.game.clocks = data.clocks;
189 this.drawOffer = data.drawOffer;
a6088c90 190 }
a6088c90
BA
191 else if (data.movesCount < L)
192 {
193 // We must tell last move to opponent
4b0384fa 194 this.st.conn.send(JSON.stringify({
a6088c90 195 code: "lastate",
6fba6e0c 196 target: this.game.oppid,
a6088c90 197 gameId: this.gameRef.id,
6fba6e0c
BA
198 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
199 score: this.game.score,
a6088c90 200 movesCount: L,
6fba6e0c
BA
201 drawOffer: this.drawOffer,
202 clocks: this.game.clocks,
a6088c90
BA
203 }));
204 }
a6088c90 205 break;
6fba6e0c 206 }
93d1d7a7
BA
207 case "resign":
208 this.$refs["basegame"].endGame(
209 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
210 break;
211 case "timeover":
212 this.$refs["basegame"].endGame(
213 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
a6088c90 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:
226 // gameconnect?
227 break;
93d1d7a7
BA
228 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
229 // ==> on "newmove", check "drawOffer" field
a6088c90
BA
230 // TODO: also use (dis)connect info to count online players?
231 case "gameconnect":
232 case "gamedisconnect":
6fba6e0c
BA
233 const online = (data.code == "gameconnect");
234 // If this is an opponent ?
235 if (this.game.oppid == data.id)
236 this.oppConnected = true;
237 else
a6088c90 238 {
6fba6e0c
BA
239 // Or an observer ?
240 if (!online)
241 delete this.people[data.id];
a6088c90 242 else
6fba6e0c 243 this.people[data.id] = data.name;
a6088c90
BA
244 }
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
BA
253 return;
254 this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid}));
2cc10cdb
BA
255 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
256 }
6fba6e0c
BA
257 else if (this.drawOffer == "sent")
258 this.drawOffer = "";
259 else
260 {
261 if (!confirm("Offer draw?"))
262 return;
2cc10cdb 263 this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid}));
a6088c90
BA
264 }
265 },
266 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
267 receiveDrawOffer: function() {
268 //if (...)
269 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
270 // if accept: send message "draw"
271 },
b988c726 272 abortGame: function(event) {
9aa229f3 273 let modalBox = document.getElementById("modalAbort");
b988c726
BA
274 if (!event)
275 {
276 // First call show options:
b988c726
BA
277 modalBox.checked = true;
278 }
279 else
280 {
9aa229f3
BA
281 modalBox.checked = false; //decision made: box disappear
282 const message = event.target.innerText;
d4036efe 283 // Next line will trigger a "gameover" event, bubbling up till here
9aa229f3 284 this.$refs["basegame"].endGame("?", "Abort: " + message);
6fba6e0c
BA
285 this.st.conn.send(JSON.stringify({
286 code: "abort",
287 msg: message,
288 target: this.game.oppid,
289 }));
b988c726 290 }
a6088c90
BA
291 },
292 resign: function(e) {
293 if (!confirm("Resign the game?"))
294 return;
6fba6e0c
BA
295 this.st.conn.send(JSON.stringify({
296 code: "resign",
297 target: this.game.oppid,
298 }));
93d1d7a7 299 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
300 this.$refs["basegame"].endGame(
301 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 302 },
967a2686
BA
303 // 3 cases for loading a game:
304 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
305 // - from server (one correspondance game I play[ed] or not)
306 // - from remote peer (one live game I don't play, finished or not)
967a2686
BA
307 loadGame: function(game) {
308 const afterRetrieval = async (game) => {
fd7aea36
BA
309 // NOTE: variants array might not be available yet, thus the two next lines
310 const variantCell = this.st.variants.filter(v => v.id == game.vid);
311 const vname = (variantCell.length > 0 ? variantCell[0].name : "");
312 if (!game.fen)
313 game.fen = game.fenStart; //game wasn't started
c0b27606
BA
314 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
315 if (gtype == "corr")
316 {
317 // corr game: needs to compute the clocks + initime
318 //if (game.players[i].rtime < 0) initime = Date.now(), else compute,
319 //also using move.played fields
320 game.clocks = [-1, -1];
321 game.initime = [0, 0];
22efa391 322 // TODO: compute clocks + initime
c0b27606 323 }
66d03f23 324 const tc = extractTime(game.timeControl);
3d55deea
BA
325 // TODO: this is not really beautiful (uid on corr players...)
326 if (gtype == "corr" && game.players[0].color == "b")
327 [ game.players[0], game.players[1] ] = [ game.players[1], game.players[0] ];
328 const myIdx = game.players.findIndex(p => {
329 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
330 });
66d03f23
BA
331 if (game.clocks[0] < 0) //game unstarted
332 {
333 game.clocks = [tc.mainTime, tc.mainTime];
334 game.initime[0] = Date.now();
cf742aaf 335 if (myIdx >= 0 && gtype == "live")
22efa391 336 {
cf742aaf 337 // I play in this live game; corr games don't have clocks+initime
d18bfa12 338 GameStorage.update(game.id,
22efa391
BA
339 {
340 clocks: game.clocks,
341 initime: game.initime,
342 });
343 }
66d03f23 344 }
a9b131f1 345 const vModule = await import("@/variants/" + vname + ".js");
d4036efe 346 window.V = vModule.VariantRules;
809ba2aa 347 this.vr = new V(game.fen);
d18bfa12
BA
348
349
350
351//TODO: people, on connect, search for opponent.......
352console.log(myIdx + " " + game.players[1-myIdx].sid); //otherwise this is undefined:
353
354
355
4b0384fa
BA
356 this.game = Object.assign({},
357 game,
cf742aaf 358 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 359 {
c0b27606 360 type: gtype,
66d03f23 361 increment: tc.increment,
a9b131f1 362 vname: vname,
6fba6e0c
BA
363 mycolor: [undefined,"w","b"][myIdx+1],
364 // opponent sid not strictly required, but easier
365 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
366 }
4b0384fa 367 );
6fba6e0c
BA
368 if (!!this.game.oppid)
369 {
370 // Send ping to server (answer pong if players[s] are connected)
a36a09c0 371 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
6fba6e0c 372 }
967a2686
BA
373 };
374 if (!!game)
375 return afterRetrival(game);
376 if (!!this.gameRef.rid)
377 {
7e1a1fe9 378 this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid}));
967a2686
BA
379 // TODO: just send a game request message to the remote player,
380 // and when receiving answer just call loadGame(received_game)
381 // + remote peer should have registered us as an observer
382 // (send moves updates + resign/abort/draw actions)
967a2686
BA
383 }
384 else
385 {
386 GameStorage.get(this.gameRef.id, async (game) => {
387 afterRetrieval(game);
388 });
389 }
a6088c90 390 },
9d54ab89 391 // Post-process a move (which was just played)
ce87ac6a 392 processMove: function(move) {
b4fb1612
BA
393 if (!this.game.mycolor)
394 return; //I'm just an observer
9d54ab89 395 // Update storage (corr or live)
6fba6e0c 396 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89
BA
397 // https://stackoverflow.com/a/38750895
398 const allowed_fields = ["appear", "vanish", "start", "end"];
399 const filtered_move = Object.keys(move)
400 .filter(key => allowed_fields.includes(key))
401 .reduce((obj, key) => {
8a7452b5 402 obj[key] = move[key];
9d54ab89
BA
403 return obj;
404 }, {});
b4fb1612 405 // Send move ("newmove" event) to opponent(s) (if ours)
dce792f6 406 let addTime = 0;
9d54ab89 407 if (move.color == this.game.mycolor)
b4fb1612 408 {
dce792f6
BA
409 if (this.game.moves.length >= 2) //after first move
410 {
411 const elapsed = Date.now() - this.game.initime[colorIdx];
412 // elapsed time is measured in milliseconds
413 addTime = this.game.increment - elapsed/1000;
414 }
6fba6e0c
BA
415 this.st.conn.send(JSON.stringify({
416 code: "newmove",
417 target: this.game.oppid,
418 move: Object.assign({}, filtered_move, {addTime: addTime}),
419 }));
b4fb1612 420 }
5b87454c
BA
421 else
422 addTime = move.addTime; //supposed transmitted
6fba6e0c 423 const nextIdx = ["w","b"].indexOf(this.vr.turn);
967a2686
BA
424 GameStorage.update(this.gameRef.id,
425 {
9d54ab89
BA
426 move: filtered_move,
427 fen: move.fen,
22efa391
BA
428 clocks: this.game.clocks.map((t,i) => i==colorIdx
429 ? this.game.clocks[i] + addTime
430 : this.game.clocks[i]),
431 initime: this.game.initime.map((t,i) => i==nextIdx
432 ? Date.now()
433 : this.game.initime[i]),
9d54ab89 434 });
967a2686
BA
435 // Also update current game object:
436 this.game.moves.push(move);
437 this.game.fen = move.fen;
66d03f23
BA
438 //TODO: just this.game.clocks[colorIdx] += addTime;
439 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
809ba2aa 440 this.game.initime[nextIdx] = Date.now();
b4fb1612 441 },
93d1d7a7 442 // TODO: this update function should also work for corr games
b4fb1612 443 gameOver: function(score) {
93d1d7a7 444 this.game.mode = "analyze";
d18bfa12 445 this.game.score = score;
22efa391 446 GameStorage.update(this.gameRef.id, { score: score });
ce87ac6a 447 },
a6088c90
BA
448 },
449};
450</script>
7e1a1fe9
BA
451
452<style lang="sass">
453// TODO
454</style>