6cb75f47339d9e4872217817fd31c01299706e74
[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: also show players names
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 <!--
26 // TODO: movelist dans basegame et chat ici
27 // ==> après, implémenter/vérifier les passages de challenges + parties en cours
28 // observer,
29 // + problèmes, habiller et publier. (+ corr...)
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 ?)
39 -->
40
41 <script>
42 import BaseGame from "@/components/BaseGame.vue";
43 //import Chat from "@/components/Chat.vue";
44 //import MoveList from "@/components/MoveList.vue";
45 import { store } from "@/store";
46 import { GameStorage } from "@/utils/gameStorage";
47 import { ppt } from "@/utils/datetime";
48 import { extractTime } from "@/utils/timeControl";
49
50 export default {
51 name: 'my-game',
52 components: {
53 BaseGame,
54 },
55 // gameRef: to find the game in (potentially remote) storage
56 data: function() {
57 return {
58 st: store.state,
59 gameRef: { //given in URL (rid = remote ID)
60 id: "",
61 rid: ""
62 },
63 game: { }, //passed to BaseGame
64 oppConnected: false,
65 corrMsg: "", //to send offline messages in corr games
66 virtualClocks: [0, 0], //initialized with true game.clocks
67 vr: null, //"variant rules" object initialized from FEN
68 drawOffer: "", //TODO: use for button style
69 people: [ ], //potential observers (TODO)
70 };
71 },
72 watch: {
73 '$route' (to, from) {
74 if (!!to.params["id"])
75 {
76 this.gameRef.id = to.params["id"];
77 this.gameRef.rid = to.query["rid"];
78 this.loadGame();
79 }
80 },
81 "game.clocks": function(newState) {
82 this.virtualClocks = newState.map(s => ppt(s));
83 const currentTurn = this.vr.turn;
84 const colorIdx = ["w","b"].indexOf(currentTurn);
85 let countdown = newState[colorIdx] -
86 (Date.now() - this.game.initime[colorIdx])/1000;
87 const myTurn = (currentTurn == this.game.mycolor);
88 let clockUpdate = setInterval(() => {
89 if (countdown <= 0 || this.vr.turn != currentTurn)
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");
96 this.st.conn.send(JSON.stringify({
97 code: "timeover",
98 target: this.game.oppid,
99 }));
100 }
101 }
102 else
103 {
104 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
105 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
106 }
107 }, 1000);
108 },
109 // In case variants array was't loaded when game was retrieved
110 "st.variants": function(variantArray) {
111 if (!!this.game.vname && this.game.vname == "")
112 this.game.vname = variantArray.filter(v => v.id == this.game.vid)[0].name;
113 },
114 },
115 created: function() {
116 if (!!this.$route.params["id"])
117 {
118 this.gameRef.id = this.$route.params["id"];
119 this.gameRef.rid = this.$route.query["rid"];
120 this.loadGame();
121 }
122 // TODO: onopen, ask lastState informations + update observers and players status
123 const socketCloseListener = () => {
124 store.socketCloseListener(); //reinitialize connexion (in store.js)
125 this.st.conn.addEventListener('message', this.socketMessageListener);
126 this.st.conn.addEventListener('close', socketCloseListener);
127 };
128 this.st.conn.onmessage = this.socketMessageListener;
129 this.st.conn.onclose = socketCloseListener;
130 },
131 methods: {
132 socketMessageListener: function(msg) {
133 const data = JSON.parse(msg.data);
134 switch (data.code)
135 {
136 case "newmove":
137 // NOTE: next call will trigger processMove()
138 this.$refs["basegame"].play(data.move,
139 "receive", this.game.vname!="Dark" ? "animate" : null);
140 break;
141 case "pong": //received if we sent a ping (game still alive on our side)
142 {
143 this.oppConnected = true;
144 // Send our "last state" informations to opponent(s)
145 const L = this.game.moves.length;
146 this.st.conn.send(JSON.stringify({
147 code: "lastate",
148 target: this.game.oppid,
149 gameId: this.gameRef.id,
150 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
151 score: this.game.score,
152 movesCount: L,
153 drawOffer: this.drawOffer,
154 clocks: this.game.clocks,
155 }));
156 break;
157 }
158 case "lastate": //got opponent infos about last move
159 {
160 const L = this.game.moves.length;
161 if (this.gameRef.id != data.gameId)
162 break; //games IDs don't match: nothing we can do...
163 // OK, opponent still in game (which might be over)
164 if (data.movesCount > L)
165 {
166 // Just got last move from him
167 this.$refs["basegame"].play(data.lastMove, "receive");
168 if (data.score != "*" && this.game.score == "*")
169 {
170 // Opponent resigned or aborted game, or accepted draw offer
171 // (this is not a stalemate or checkmate)
172 this.$refs["basegame"].endGame(data.score, "Opponent action");
173 }
174 this.game.clocks = data.clocks;
175 this.drawOffer = data.drawOffer;
176 }
177 else if (data.movesCount < L)
178 {
179 // We must tell last move to opponent
180 this.st.conn.send(JSON.stringify({
181 code: "lastate",
182 target: this.game.oppid,
183 gameId: this.gameRef.id,
184 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
185 score: this.game.score,
186 movesCount: L,
187 drawOffer: this.drawOffer,
188 clocks: this.game.clocks,
189 }));
190 }
191 break;
192 }
193 case "resign":
194 this.$refs["basegame"].endGame(
195 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
196 break;
197 case "timeover":
198 this.$refs["basegame"].endGame(
199 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
200 break;
201 case "abort":
202 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
203 break;
204 case "draw":
205 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
206 break;
207 case "drawoffer":
208 this.drawOffer = "received";
209 break;
210 case "askfullgame":
211 // TODO: just give game; observers are listed here anyway:
212 // gameconnect?
213 break;
214 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
215 // ==> on "newmove", check "drawOffer" field
216 // TODO: also use (dis)connect info to count online players?
217 case "gameconnect":
218 case "gamedisconnect":
219 const online = (data.code == "gameconnect");
220 // If this is an opponent ?
221 if (this.game.oppid == data.id)
222 this.oppConnected = true;
223 else
224 {
225 // Or an observer ?
226 if (!online)
227 delete this.people[data.id];
228 else
229 this.people[data.id] = data.name;
230 }
231 break;
232 }
233 },
234 offerDraw: function() {
235 // TODO: also for corr games
236 if (this.drawOffer == "received")
237 {
238 if (!confirm("Accept draw?"))
239 return;
240 this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid}));
241 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
242 }
243 else if (this.drawOffer == "sent")
244 this.drawOffer = "";
245 else
246 {
247 if (!confirm("Offer draw?"))
248 return;
249 this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid}));
250 }
251 },
252 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
253 receiveDrawOffer: function() {
254 //if (...)
255 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
256 // if accept: send message "draw"
257 },
258 abortGame: function(event) {
259 let modalBox = document.getElementById("modalAbort");
260 if (!event)
261 {
262 // First call show options:
263 modalBox.checked = true;
264 }
265 else
266 {
267 modalBox.checked = false; //decision made: box disappear
268 const message = event.target.innerText;
269 // Next line will trigger a "gameover" event, bubbling up till here
270 this.$refs["basegame"].endGame("?", "Abort: " + message);
271 this.st.conn.send(JSON.stringify({
272 code: "abort",
273 msg: message,
274 target: this.game.oppid,
275 }));
276 }
277 },
278 resign: function(e) {
279 if (!confirm("Resign the game?"))
280 return;
281 this.st.conn.send(JSON.stringify({
282 code: "resign",
283 target: this.game.oppid,
284 }));
285 // Next line will trigger a "gameover" event, bubbling up till here
286 this.$refs["basegame"].endGame(
287 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
288 },
289 // 3 cases for loading a game:
290 // - from indexedDB (running or completed live game I play)
291 // - from server (one correspondance game I play[ed] or not)
292 // - from remote peer (one live game I don't play, finished or not)
293 loadGame: function(game) {
294 const afterRetrieval = async (game) => {
295 // NOTE: variants array might not be available yet, thus the two next lines
296 const variantCell = this.st.variants.filter(v => v.id == game.vid);
297 const vname = (variantCell.length > 0 ? variantCell[0].name : "");
298 if (!game.fen)
299 game.fen = game.fenStart; //game wasn't started
300
301
302 // TODO: process rtime, clocks............ game.clocks doesn't exist anymore
303 console.log(game);
304
305 const tc = extractTime(game.timeControl);
306 if (game.clocks[0] < 0) //game unstarted
307 {
308 game.clocks = [tc.mainTime, tc.mainTime];
309 game.initime[0] = Date.now();
310 }
311 const vModule = await import("@/variants/" + vname + ".js");
312 window.V = vModule.VariantRules;
313 this.vr = new V(game.fen);
314 const myIdx = game.players.findIndex(p => p.sid == this.st.user.sid);
315 this.game = Object.assign({},
316 game,
317 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
318 {
319 increment: tc.increment,
320 vname: vname,
321 mycolor: [undefined,"w","b"][myIdx+1],
322 // opponent sid not strictly required, but easier
323 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
324 }
325 );
326 if (!!this.game.oppid)
327 {
328 // Send ping to server (answer pong if players[s] are connected)
329 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
330 }
331 };
332 if (!!game)
333 return afterRetrival(game);
334 if (!!this.gameRef.rid)
335 {
336 this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid}));
337 // TODO: just send a game request message to the remote player,
338 // and when receiving answer just call loadGame(received_game)
339 // + remote peer should have registered us as an observer
340 // (send moves updates + resign/abort/draw actions)
341 }
342 else
343 {
344 GameStorage.get(this.gameRef.id, async (game) => {
345 afterRetrieval(game);
346 });
347 }
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"].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.st.conn.send(JSON.stringify({
371 code: "newmove",
372 target: this.game.oppid,
373 move: Object.assign({}, filtered_move, {addTime: addTime}),
374 }));
375 }
376 else
377 addTime = move.addTime; //supposed transmitted
378 const nextIdx = ["w","b"].indexOf(this.vr.turn);
379 GameStorage.update(this.gameRef.id,
380 {
381 colorIdx: colorIdx,
382 nextIdx: nextIdx,
383 move: filtered_move,
384 fen: move.fen,
385 addTime: addTime,
386 });
387 // Also update current game object:
388 this.game.moves.push(move);
389 this.game.fen = move.fen;
390 //TODO: just this.game.clocks[colorIdx] += addTime;
391 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
392 this.game.initime[nextIdx] = Date.now();
393 },
394 // TODO: this update function should also work for corr games
395 gameOver: function(score) {
396 this.game.mode = "analyze";
397 GameStorage.update(this.gameRef.id,
398 {
399 score: score,
400 });
401 },
402 },
403 };
404 </script>
405
406 <style lang="sass">
407 // TODO
408 </style>