Update on game.clocks. Unfinished
[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")
5b87454c
BA
14 // TODO: virtualClocks[...], not "clockState"
15 div Time: {{ clockState }}
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
25<script>
46284a2f 26import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
27//import Chat from "@/components/Chat.vue";
28//import MoveList from "@/components/MoveList.vue";
29import { store } from "@/store";
967a2686 30import { GameStorage } from "@/utils/gameStorage";
5b87454c 31import { ppt } from "@/utils/datetime";
a6088c90
BA
32
33export default {
34 name: 'my-game',
35 components: {
36 BaseGame,
37 },
f7121527 38 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
39 data: function() {
40 return {
41 st: store.state,
4b0384fa
BA
42 gameRef: { //given in URL (rid = remote ID)
43 id: "",
44 rid: ""
45 },
46 game: { }, //passed to BaseGame
5b87454c 47 virtualClocks: [ ], //initialized with true game.clocks
6dd02928 48 vr: null, //"variant rules" object initialized from FEN
93d1d7a7 49 drawOfferSent: false, //did I just ask for draw? (TODO: use for button style)
4b0384fa 50 people: [ ], //potential observers (TODO)
a6088c90
BA
51 };
52 },
5b87454c
BA
53
54 // TODO: this method should disappear and virtualClocks already be "prettified":
55 // all computations are done when game.clocks are updated (see below)
56 computed: {
57 clockState: function() {
58 if (this.virtualClocks.length == 0)
59 return; //nothing to display for now
60 return ppt(this.virtualClocks[0]) + " - " + ppt(this.virtualClocks[1]);
61 },
62 },
63
a6088c90 64 watch: {
f7121527 65 '$route' (to, from) {
4fe5664d
BA
66 if (!!to.params["id"])
67 {
68 this.gameRef.id = to.params["id"];
69 this.gameRef.rid = to.query["rid"];
70 this.loadGame();
71 }
a6088c90 72 },
5b87454c
BA
73 "game.clocks": function(newState) {
74 this.virtualClocks = newState;
75 setInterval(function() {
76
77 // TODO: run clock of current turn, stop at 0, clearInterval in the end
78 // https://www.geeksforgeeks.org/create-countdown-timer-using-javascript/
79 // if it was my turn, call gameOver. Otherwise just stay at 0 and wait.
80 if ( ...........)
81//à 0, bloquer puis si mon temps : perte au temps. Sinon attendre message adversaire (il peut être offline).
82
83 });
84 },
a6088c90 85 },
a6088c90 86 created: function() {
f7121527 87 if (!!this.$route.params["id"])
a6088c90 88 {
f7121527
BA
89 this.gameRef.id = this.$route.params["id"];
90 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 91 this.loadGame();
f7121527 92 }
f7121527
BA
93 // TODO: how to know who is observing ? Send message to everyone with game ID ?
94 // and then just listen to (dis)connect events
3b450453
BA
95 // server always send "connect on " + URL ; then add to observers if game...
96 // detect multiple tabs connected (when connect ask server if my SID is already in use)
97// router when access a game page tell to server I joined + game ID (no need rid)
98// and ask server for current joined (= observers)
99// when send to chat (or a move), reach only this group (send gid along)
3b450453
BA
100 // --> doivent être enregistrés comme observers au niveau du serveur...
101 // non: poll users + events startObserving / stopObserving
b4fb1612 102 // (à faire au niveau du routeur ?)
3b450453 103
a6088c90
BA
104 // TODO: also handle "draw accepted" (use opponents array?)
105 // --> must give this info also when sending lastState...
106 // and, if all players agree then OK draw (end game ...etc)
107 const socketMessageListener = msg => {
108 const data = JSON.parse(msg.data);
109 let L = undefined;
110 switch (data.code)
111 {
f7121527 112 case "newmove":
c4f91d3f
BA
113 // NOTE: next call will trigger processMove()
114 this.$refs["basegame"].play(data.move,
115 "receive", this.game.vname!="Dark" ? "animate" : null);
a6088c90
BA
116 break;
117 case "pong": //received if we sent a ping (game still alive on our side)
118 if (this.gameRef.id != data.gameId)
f7121527 119 break; //games IDs don't match: the game is definitely over...
a6088c90
BA
120 this.oppConnected = true;
121 // Send our "last state" informations to opponent(s)
122 L = this.vr.moves.length;
123 Object.keys(this.opponents).forEach(oid => {
4b0384fa 124 this.st.conn.send(JSON.stringify({
a6088c90
BA
125 code: "lastate",
126 oppid: oid,
127 gameId: this.gameRef.id,
128 lastMove: (L>0?this.vr.moves[L-1]:undefined),
129 movesCount: L,
130 }));
131 });
132 break;
f7121527 133 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
93d1d7a7 134 // TODO: need to send along clock state (my current time) with my last move
a6088c90
BA
135 case "lastate": //got opponent infos about last move
136 L = this.vr.moves.length;
137 if (this.gameRef.id != data.gameId)
138 break; //games IDs don't match: nothing we can do...
139 // OK, opponent still in game (which might be over)
140 if (this.score != "*")
141 {
142 // We finished the game (any result possible)
4b0384fa 143 this.st.conn.send(JSON.stringify({
a6088c90
BA
144 code: "lastate",
145 oppid: data.oppid,
146 gameId: this.gameRef.id,
147 score: this.score,
148 }));
149 }
150 else if (!!data.score) //opponent finished the game
151 this.endGame(data.score);
152 else if (data.movesCount < L)
153 {
154 // We must tell last move to opponent
4b0384fa 155 this.st.conn.send(JSON.stringify({
a6088c90
BA
156 code: "lastate",
157 oppid: this.opponent.id,
158 gameId: this.gameRef.id,
159 lastMove: this.vr.moves[L-1],
160 movesCount: L,
161 }));
162 }
163 else if (data.movesCount > L) //just got last move from him
c4f91d3f 164 this.play(data.lastMove, "animate"); //TODO: wrong call (3 args)
a6088c90 165 break;
93d1d7a7
BA
166 case "resign":
167 this.$refs["basegame"].endGame(
168 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
169 break;
170 case "timeover":
171 this.$refs["basegame"].endGame(
172 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
a6088c90 173 break;
93d1d7a7
BA
174 case "abort":
175 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
176 break;
177 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
178 // ==> on "newmove", check "drawOffer" field
a6088c90
BA
179 // TODO: also use (dis)connect info to count online players?
180 case "gameconnect":
181 case "gamedisconnect":
182 if (this.mode=="human")
183 {
184 const online = (data.code == "connect");
185 // If this is an opponent ?
186 if (!!this.opponents[data.id])
187 this.opponents[data.id].online = online;
188 else
189 {
190 // Or an observer ?
191 if (!online)
192 delete this.people[data.id];
193 else
194 this.people[data.id] = data.name;
195 }
196 }
197 break;
198 }
199 };
200 const socketCloseListener = () => {
4b0384fa
BA
201 this.st.conn.addEventListener('message', socketMessageListener);
202 this.st.conn.addEventListener('close', socketCloseListener);
a6088c90 203 };
4b0384fa
BA
204 this.st.conn.onmessage = socketMessageListener;
205 this.st.conn.onclose = socketCloseListener;
a6088c90
BA
206 },
207 // dans variant.js (plutôt room.js) conn gère aussi les challenges
208 // et les chats dans chat.js. Puis en webRTC, repenser tout ça.
209 methods: {
210 offerDraw: function() {
211 if (!confirm("Offer draw?"))
212 return;
213 // Stay in "draw offer sent" state until next move is played
214 this.drawOfferSent = true;
215 if (this.subMode == "corr")
216 {
217 // TODO: set drawOffer on in game (how ?)
218 }
219 else //live game
220 {
221 this.opponents.forEach(o => {
222 if (!!o.online)
223 {
224 try {
4b0384fa 225 this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
a6088c90
BA
226 } catch (INVALID_STATE_ERR) {
227 return;
228 }
229 }
230 });
231 }
232 },
233 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
234 receiveDrawOffer: function() {
235 //if (...)
236 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
237 // if accept: send message "draw"
238 },
b988c726
BA
239 abortGame: function(event) {
240 if (!event)
241 {
242 // First call show options:
243 let modalBox = document.getElementById("modalAbort");
244 modalBox.checked = true;
245 }
246 else
247 {
248 console.log(event);
d4036efe 249 return;
b988c726 250 //const message = event.
d4036efe
BA
251 // Next line will trigger a "gameover" event, bubbling up till here
252 this.$refs["basegame"].endGame("?");
b988c726
BA
253 this.game.players.forEach(p => {
254 if (!!p.sid && p.sid != this.st.user.sid)
255 {
256 this.st.conn.send(JSON.stringify({
257 code: "abort",
258 msg: message,
259 target: p.sid,
260 }));
261 }
262 });
263 }
a6088c90
BA
264 },
265 resign: function(e) {
266 if (!confirm("Resign the game?"))
267 return;
93d1d7a7
BA
268 this.game.players.forEach(p => {
269 if (!!p.sid && p.sid != this.st.user.sid)
270 {
271 this.st.conn.send(JSON.stringify({
272 code: "resign",
273 target: p.sid,
274 }));
a6088c90 275 }
93d1d7a7
BA
276 });
277 // Next line will trigger a "gameover" event, bubbling up till here
278 this.$refs["basegame"].endGame(this.game.mycolor=="w" ? "0-1" : "1-0");
a6088c90 279 },
967a2686
BA
280 // 3 cases for loading a game:
281 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
282 // - from server (one correspondance game I play[ed] or not)
283 // - from remote peer (one live game I don't play, finished or not)
967a2686
BA
284 loadGame: function(game) {
285 const afterRetrieval = async (game) => {
d4036efe
BA
286 const vModule = await import("@/variants/" + game.vname + ".js");
287 window.V = vModule.VariantRules;
288 this.vr = new V(game.fenStart);
4b0384fa
BA
289 this.game = Object.assign({},
290 game,
291 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
b4fb1612
BA
292 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
293 p => p.sid == this.st.user.sid)]},
4b0384fa 294 );
967a2686
BA
295 };
296 if (!!game)
297 return afterRetrival(game);
298 if (!!this.gameRef.rid)
299 {
300 // TODO: just send a game request message to the remote player,
301 // and when receiving answer just call loadGame(received_game)
302 // + remote peer should have registered us as an observer
303 // (send moves updates + resign/abort/draw actions)
304 return;
305 }
306 else
307 {
308 GameStorage.get(this.gameRef.id, async (game) => {
309 afterRetrieval(game);
310 });
311 }
4fe5664d
BA
312// // Poll all players except me (if I'm playing) to know online status.
313// // --> Send ping to server (answer pong if players[s] are connected)
314// if (this.gameInfo.players.some(p => p.sid == this.st.user.sid))
315// {
316// this.game.players.forEach(p => {
317// if (p.sid != this.st.user.sid)
318// this.st.conn.send(JSON.stringify({code:"ping", oppid:p.sid}));
319// });
320// }
a6088c90 321 },
b4fb1612 322 // TODO: refactor this old "oppConnected" logic
6ec161b9
BA
323// oppConnected: function(uid) {
324// return this.opponents.some(o => o.id == uid && o.online);
325// },
9d54ab89 326 // Post-process a move (which was just played)
ce87ac6a 327 processMove: function(move) {
b4fb1612
BA
328 if (!this.game.mycolor)
329 return; //I'm just an observer
9d54ab89 330 // Update storage (corr or live)
c4f91d3f 331 const colorIdx = ["w","b","g","r"].indexOf(move.color);
9d54ab89
BA
332 // https://stackoverflow.com/a/38750895
333 const allowed_fields = ["appear", "vanish", "start", "end"];
334 const filtered_move = Object.keys(move)
335 .filter(key => allowed_fields.includes(key))
336 .reduce((obj, key) => {
8a7452b5 337 obj[key] = move[key];
9d54ab89
BA
338 return obj;
339 }, {});
b4fb1612 340 // Send move ("newmove" event) to opponent(s) (if ours)
c4f91d3f 341 let addTime = undefined;
9d54ab89 342 if (move.color == this.game.mycolor)
b4fb1612 343 {
967a2686 344 const elapsed = Date.now() - this.game.initime;
5b87454c
BA
345 // elapsed time is measured in milliseconds
346 addTime = this.game.increment - elapsed/1000;
b4fb1612
BA
347 this.game.players.forEach(p => {
348 if (p.sid != this.st.user.sid)
93d1d7a7 349 {
8a7452b5
BA
350 this.st.conn.send(JSON.stringify({
351 code: "newmove",
9d54ab89 352 target: p.sid,
5b87454c 353 move: Object.assign({}, filtered_move, {addTime: addTime}),
8a7452b5 354 }));
93d1d7a7 355 }
b4fb1612
BA
356 });
357 }
5b87454c
BA
358 else
359 addTime = move.addTime; //supposed transmitted
967a2686
BA
360 const myTurnNow = (this.vr.turn == this.game.mycolor);
361 GameStorage.update(this.gameRef.id,
362 {
9d54ab89
BA
363 colorIdx: colorIdx,
364 move: filtered_move,
365 fen: move.fen,
c4f91d3f 366 addTime: addTime,
967a2686 367 initime: myTurnNow,
9d54ab89 368 });
967a2686
BA
369 // Also update current game object:
370 this.game.moves.push(move);
371 this.game.fen = move.fen;
372 this.game.clocks[colorIdx] += (!!addTime ? addTime : 0);
373 this.game.initime = (myTurnNow ? Date.now() : undefined);
b4fb1612 374 },
93d1d7a7 375 // TODO: this update function should also work for corr games
b4fb1612 376 gameOver: function(score) {
93d1d7a7 377 this.game.mode = "analyze";
5b87454c
BA
378 GameStorage.update(this.gameRef.id,
379 {
9d54ab89
BA
380 score: score,
381 });
ce87ac6a 382 },
a6088c90
BA
383 },
384};
385</script>