803751eb519a31ea00db94cbc092688768bc0825
[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
49 export default {
50 name: 'my-game',
51 components: {
52 BaseGame,
53 },
54 // gameRef: to find the game in (potentially remote) storage
55 data: function() {
56 return {
57 st: store.state,
58 gameRef: { //given in URL (rid = remote ID)
59 id: "",
60 rid: ""
61 },
62 game: { }, //passed to BaseGame
63 oppConnected: false,
64 corrMsg: "", //to send offline messages in corr games
65 virtualClocks: [0, 0], //initialized with true game.clocks
66 vr: null, //"variant rules" object initialized from FEN
67 drawOffer: "", //TODO: use for button style
68 people: [ ], //potential observers (TODO)
69 };
70 },
71 watch: {
72 '$route' (to, from) {
73 if (!!to.params["id"])
74 {
75 this.gameRef.id = to.params["id"];
76 this.gameRef.rid = to.query["rid"];
77 this.loadGame();
78 }
79 },
80 "game.clocks": function(newState) {
81 this.virtualClocks = newState.map(s => ppt(s));
82 const currentTurn = this.vr.turn;
83 const colorIdx = ["w","b"].indexOf(currentTurn);
84 let countdown = newState[colorIdx] -
85 (Date.now() - this.game.initime[colorIdx])/1000;
86 const myTurn = (currentTurn == this.game.mycolor);
87 let clockUpdate = setInterval(() => {
88 if (countdown <= 0 || this.vr.turn != currentTurn)
89 {
90 clearInterval(clockUpdate);
91 if (countdown <= 0 && myTurn)
92 {
93 this.$refs["basegame"].endGame(
94 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
95 this.st.conn.send(JSON.stringify({
96 code: "timeover",
97 target: this.game.oppid,
98 }));
99 }
100 }
101 else
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 }
106 }, 1000);
107 },
108 },
109 created: function() {
110 if (!!this.$route.params["id"])
111 {
112 this.gameRef.id = this.$route.params["id"];
113 this.gameRef.rid = this.$route.query["rid"];
114 this.loadGame();
115 }
116 const socketMessageListener = msg => {
117 const data = JSON.parse(msg.data);
118 switch (data.code)
119 {
120 case "newmove":
121 // NOTE: next call will trigger processMove()
122 this.$refs["basegame"].play(data.move,
123 "receive", this.game.vname!="Dark" ? "animate" : null);
124 break;
125 case "pong": //received if we sent a ping (game still alive on our side)
126 {
127 this.oppConnected = true;
128 // Send our "last state" informations to opponent(s)
129 const L = this.game.moves.length;
130 this.st.conn.send(JSON.stringify({
131 code: "lastate",
132 target: this.game.oppid,
133 gameId: this.gameRef.id,
134 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
135 score: this.game.score,
136 movesCount: L,
137 drawOffer: this.drawOffer,
138 clocks: this.game.clocks,
139 }));
140 break;
141 }
142 case "lastate": //got opponent infos about last move
143 {
144 const L = this.game.moves.length;
145 if (this.gameRef.id != data.gameId)
146 break; //games IDs don't match: nothing we can do...
147 // OK, opponent still in game (which might be over)
148 if (data.movesCount > L)
149 {
150 // Just got last move from him
151 this.$refs["basegame"].play(data.lastMove, "receive");
152 if (data.score != "*" && this.game.score == "*")
153 {
154 // Opponent resigned or aborted game, or accepted draw offer
155 // (this is not a stalemate or checkmate)
156 this.$refs["basegame"].endGame(data.score, "Opponent action");
157 }
158 this.game.clocks = data.clocks;
159 this.drawOffer = data.drawOffer;
160 }
161 else if (data.movesCount < L)
162 {
163 // We must tell last move to opponent
164 this.st.conn.send(JSON.stringify({
165 code: "lastate",
166 target: this.game.oppid,
167 gameId: this.gameRef.id,
168 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
169 score: this.game.score,
170 movesCount: L,
171 drawOffer: this.drawOffer,
172 clocks: this.game.clocks,
173 }));
174 }
175 break;
176 }
177 case "resign":
178 this.$refs["basegame"].endGame(
179 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
180 break;
181 case "timeover":
182 this.$refs["basegame"].endGame(
183 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
184 break;
185 case "abort":
186 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
187 break;
188 case "draw":
189 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
190 break;
191 case "drawoffer":
192 this.drawOffer = "received";
193 break;
194 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
195 // ==> on "newmove", check "drawOffer" field
196 // TODO: also use (dis)connect info to count online players?
197 case "gameconnect":
198 case "gamedisconnect":
199 const online = (data.code == "gameconnect");
200 // If this is an opponent ?
201 if (this.game.oppid == data.id)
202 this.oppConnected = true;
203 else
204 {
205 // Or an observer ?
206 if (!online)
207 delete this.people[data.id];
208 else
209 this.people[data.id] = data.name;
210 }
211 break;
212 }
213 };
214 // TODO: onopen, ask lastState informations + update observers and players status
215 const socketCloseListener = () => {
216 this.st.conn.addEventListener('message', socketMessageListener);
217 this.st.conn.addEventListener('close', socketCloseListener);
218 };
219 this.st.conn.onmessage = socketMessageListener;
220 this.st.conn.onclose = socketCloseListener;
221 },
222 methods: {
223 offerDraw: function() {
224 // TODO: also for corr games
225 if (this.drawOffer == "received")
226 {
227 if (!confirm("Accept draw?"))
228 return;
229 this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid}));
230 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
231 }
232 else if (this.drawOffer == "sent")
233 this.drawOffer = "";
234 else
235 {
236 if (!confirm("Offer draw?"))
237 return;
238 this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid}));
239 }
240 },
241 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
242 receiveDrawOffer: function() {
243 //if (...)
244 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
245 // if accept: send message "draw"
246 },
247 abortGame: function(event) {
248 let modalBox = document.getElementById("modalAbort");
249 if (!event)
250 {
251 // First call show options:
252 modalBox.checked = true;
253 }
254 else
255 {
256 modalBox.checked = false; //decision made: box disappear
257 const message = event.target.innerText;
258 // Next line will trigger a "gameover" event, bubbling up till here
259 this.$refs["basegame"].endGame("?", "Abort: " + message);
260 this.st.conn.send(JSON.stringify({
261 code: "abort",
262 msg: message,
263 target: this.game.oppid,
264 }));
265 }
266 },
267 resign: function(e) {
268 if (!confirm("Resign the game?"))
269 return;
270 this.st.conn.send(JSON.stringify({
271 code: "resign",
272 target: this.game.oppid,
273 }));
274 // Next line will trigger a "gameover" event, bubbling up till here
275 this.$refs["basegame"].endGame(
276 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
277 },
278 // 3 cases for loading a game:
279 // - from indexedDB (running or completed live game I play)
280 // - from server (one correspondance game I play[ed] or not)
281 // - from remote peer (one live game I don't play, finished or not)
282 loadGame: function(game) {
283 const afterRetrieval = async (game) => {
284 const vModule = await import("@/variants/" + game.vname + ".js");
285 window.V = vModule.VariantRules;
286 this.vr = new V(game.fen);
287 const myIdx = game.players.findIndex(p => p.sid == this.st.user.sid);
288 this.game = Object.assign({},
289 game,
290 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
291 {
292 mycolor: [undefined,"w","b"][myIdx+1],
293 // opponent sid not strictly required, but easier
294 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
295 }
296 );
297 if (!!this.game.oppid)
298 {
299 // Send ping to server (answer pong if players[s] are connected)
300 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
301 }
302 };
303 if (!!game)
304 return afterRetrival(game);
305 if (!!this.gameRef.rid)
306 {
307 // TODO: just send a game request message to the remote player,
308 // and when receiving answer just call loadGame(received_game)
309 // + remote peer should have registered us as an observer
310 // (send moves updates + resign/abort/draw actions)
311 }
312 else
313 {
314 GameStorage.get(this.gameRef.id, async (game) => {
315 afterRetrieval(game);
316 });
317 }
318 },
319 // Post-process a move (which was just played)
320 processMove: function(move) {
321 if (!this.game.mycolor)
322 return; //I'm just an observer
323 // Update storage (corr or live)
324 const colorIdx = ["w","b"].indexOf(move.color);
325 // https://stackoverflow.com/a/38750895
326 const allowed_fields = ["appear", "vanish", "start", "end"];
327 const filtered_move = Object.keys(move)
328 .filter(key => allowed_fields.includes(key))
329 .reduce((obj, key) => {
330 obj[key] = move[key];
331 return obj;
332 }, {});
333 // Send move ("newmove" event) to opponent(s) (if ours)
334 let addTime = undefined;
335 if (move.color == this.game.mycolor)
336 {
337 const elapsed = Date.now() - this.game.initime[colorIdx];
338 // elapsed time is measured in milliseconds
339 addTime = this.game.increment - elapsed/1000;
340 this.st.conn.send(JSON.stringify({
341 code: "newmove",
342 target: this.game.oppid,
343 move: Object.assign({}, filtered_move, {addTime: addTime}),
344 }));
345 }
346 else
347 addTime = move.addTime; //supposed transmitted
348 const nextIdx = ["w","b"].indexOf(this.vr.turn);
349 GameStorage.update(this.gameRef.id,
350 {
351 colorIdx: colorIdx,
352 nextIdx: nextIdx,
353 move: filtered_move,
354 fen: move.fen,
355 addTime: addTime,
356 });
357 // Also update current game object:
358 this.game.moves.push(move);
359 this.game.fen = move.fen;
360 //TODO: just this.game.clocks[colorIdx] += (!!addTime ? addTime : 0);
361 this.$set(this.game.clocks, colorIdx,
362 this.game.clocks[colorIdx] + (!!addTime ? addTime : 0));
363 this.game.initime[nextIdx] = Date.now();
364 },
365 // TODO: this update function should also work for corr games
366 gameOver: function(score) {
367 this.game.mode = "analyze";
368 GameStorage.update(this.gameRef.id,
369 {
370 score: score,
371 });
372 },
373 },
374 };
375 </script>