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