d3a4bd7b329d04be7890fe459ea0a4440cc67d2e
[vchess.git] / client / src / views / Game.vue
1 <template lang="pug">
2 .row
3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
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"] }}
12 BaseGame(:game="game" :vr="vr" ref="basegame"
13 @newmove="processMove" @gameover="gameOver")
14 // TODO: virtualClocks[...], not "clockState"
15 div Time: {{ clockState }}
16 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
17 button(@click="offerDraw") Draw
18 button(@click="() => abortGame()") Abort
19 button(@click="resign") Resign
20 div(v-if="game.mode=='corr'")
21 textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
22 div(v-show="cursor>=0") {{ moves[cursor].message }}
23 </template>
24
25 <script>
26 import BaseGame from "@/components/BaseGame.vue";
27 //import Chat from "@/components/Chat.vue";
28 //import MoveList from "@/components/MoveList.vue";
29 import { store } from "@/store";
30 import { GameStorage } from "@/utils/gameStorage";
31 import { ppt } from "@/utils/datetime";
32
33 export default {
34 name: 'my-game',
35 components: {
36 BaseGame,
37 },
38 // gameRef: to find the game in (potentially remote) storage
39 data: function() {
40 return {
41 st: store.state,
42 gameRef: { //given in URL (rid = remote ID)
43 id: "",
44 rid: ""
45 },
46 game: { }, //passed to BaseGame
47 virtualClocks: [ ], //initialized with true game.clocks
48 vr: null, //"variant rules" object initialized from FEN
49 drawOfferSent: false, //did I just ask for draw? (TODO: use for button style)
50 people: [ ], //potential observers (TODO)
51 };
52 },
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
64 watch: {
65 '$route' (to, from) {
66 if (!!to.params["id"])
67 {
68 this.gameRef.id = to.params["id"];
69 this.gameRef.rid = to.query["rid"];
70 this.loadGame();
71 }
72 },
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 },
85 },
86 created: function() {
87 if (!!this.$route.params["id"])
88 {
89 this.gameRef.id = this.$route.params["id"];
90 this.gameRef.rid = this.$route.query["rid"];
91 this.loadGame();
92 }
93 // TODO: how to know who is observing ? Send message to everyone with game ID ?
94 // and then just listen to (dis)connect events
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)
100 // --> doivent être enregistrés comme observers au niveau du serveur...
101 // non: poll users + events startObserving / stopObserving
102 // (à faire au niveau du routeur ?)
103
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 {
112 case "newmove":
113 // NOTE: next call will trigger processMove()
114 this.$refs["basegame"].play(data.move,
115 "receive", this.game.vname!="Dark" ? "animate" : null);
116 break;
117 case "pong": //received if we sent a ping (game still alive on our side)
118 if (this.gameRef.id != data.gameId)
119 break; //games IDs don't match: the game is definitely over...
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 => {
124 this.st.conn.send(JSON.stringify({
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;
133 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
134 // TODO: need to send along clock state (my current time) with my last move
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)
143 this.st.conn.send(JSON.stringify({
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
155 this.st.conn.send(JSON.stringify({
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
164 this.play(data.lastMove, "animate"); //TODO: wrong call (3 args)
165 break;
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");
173 break;
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
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 = () => {
201 this.st.conn.addEventListener('message', socketMessageListener);
202 this.st.conn.addEventListener('close', socketCloseListener);
203 };
204 this.st.conn.onmessage = socketMessageListener;
205 this.st.conn.onclose = socketCloseListener;
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 {
225 this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
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 },
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);
249 return;
250 //const message = event.
251 // Next line will trigger a "gameover" event, bubbling up till here
252 this.$refs["basegame"].endGame("?");
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 }
264 },
265 resign: function(e) {
266 if (!confirm("Resign the game?"))
267 return;
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 }));
275 }
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");
279 },
280 // 3 cases for loading a game:
281 // - from indexedDB (running or completed live game I play)
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)
284 loadGame: function(game) {
285 const afterRetrieval = async (game) => {
286 const vModule = await import("@/variants/" + game.vname + ".js");
287 window.V = vModule.VariantRules;
288 this.vr = new V(game.fenStart);
289 this.game = Object.assign({},
290 game,
291 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
292 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
293 p => p.sid == this.st.user.sid)]},
294 );
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 }
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 // }
321 },
322 // TODO: refactor this old "oppConnected" logic
323 // oppConnected: function(uid) {
324 // return this.opponents.some(o => o.id == uid && o.online);
325 // },
326 // Post-process a move (which was just played)
327 processMove: function(move) {
328 if (!this.game.mycolor)
329 return; //I'm just an observer
330 // Update storage (corr or live)
331 const colorIdx = ["w","b","g","r"].indexOf(move.color);
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) => {
337 obj[key] = move[key];
338 return obj;
339 }, {});
340 // Send move ("newmove" event) to opponent(s) (if ours)
341 let addTime = undefined;
342 if (move.color == this.game.mycolor)
343 {
344 const elapsed = Date.now() - this.game.initime;
345 // elapsed time is measured in milliseconds
346 addTime = this.game.increment - elapsed/1000;
347 this.game.players.forEach(p => {
348 if (p.sid != this.st.user.sid)
349 {
350 this.st.conn.send(JSON.stringify({
351 code: "newmove",
352 target: p.sid,
353 move: Object.assign({}, filtered_move, {addTime: addTime}),
354 }));
355 }
356 });
357 }
358 else
359 addTime = move.addTime; //supposed transmitted
360 const myTurnNow = (this.vr.turn == this.game.mycolor);
361 GameStorage.update(this.gameRef.id,
362 {
363 colorIdx: colorIdx,
364 move: filtered_move,
365 fen: move.fen,
366 addTime: addTime,
367 initime: myTurnNow,
368 });
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);
374 },
375 // TODO: this update function should also work for corr games
376 gameOver: function(score) {
377 this.game.mode = "analyze";
378 GameStorage.update(this.gameRef.id,
379 {
380 score: score,
381 });
382 },
383 },
384 };
385 </script>