Draft game update. TODO: debug, finish view/Game.vue
[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 if (this.game.moves.length < 2)
83 {
84 // 1st move not completed yet: freeze time
85 this.virtualClocks = newState.map(s => ppt(s));
86 return;
87 }
88 const currentTurn = this.vr.turn;
89 const colorIdx = ["w","b"].indexOf(currentTurn);
90 let countdown = newState[colorIdx] -
91 (Date.now() - this.game.initime[colorIdx])/1000;
92 this.virtualClocks = [0,1].map(i => {
93 const removeTime = i == colorIdx
94 ? (Date.now() - this.game.initime[colorIdx])/1000
95 : 0;
96 return ppt(newState[i] - removeTime);
97 });
98 const myTurn = (currentTurn == this.game.mycolor);
99 let clockUpdate = setInterval(() => {
100 if (countdown <= 0 || this.vr.turn != currentTurn)
101 {
102 clearInterval(clockUpdate);
103 if (countdown <= 0 && myTurn)
104 {
105 this.$refs["basegame"].endGame(
106 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
107 this.st.conn.send(JSON.stringify({
108 code: "timeover",
109 target: this.game.oppid,
110 }));
111 }
112 }
113 else
114 {
115 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
116 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
117 }
118 }, 1000);
119 },
120 // In case variants array was't loaded when game was retrieved
121 "st.variants": function(variantArray) {
122 if (!!this.game.vname && this.game.vname == "")
123 this.game.vname = variantArray.filter(v => v.id == this.game.vid)[0].name;
124 },
125 },
126 created: function() {
127 if (!!this.$route.params["id"])
128 {
129 this.gameRef.id = this.$route.params["id"];
130 this.gameRef.rid = this.$route.query["rid"];
131 this.loadGame();
132 }
133 // TODO: onopen, ask lastState informations + update observers and players status
134 const socketCloseListener = () => {
135 store.socketCloseListener(); //reinitialize connexion (in store.js)
136 this.st.conn.addEventListener('message', this.socketMessageListener);
137 this.st.conn.addEventListener('close', socketCloseListener);
138 };
139 this.st.conn.onmessage = this.socketMessageListener;
140 this.st.conn.onclose = socketCloseListener;
141 },
142 methods: {
143 socketMessageListener: function(msg) {
144 const data = JSON.parse(msg.data);
145 switch (data.code)
146 {
147 case "newmove":
148 // NOTE: next call will trigger processMove()
149 this.$refs["basegame"].play(data.move,
150 "receive", this.game.vname!="Dark" ? "animate" : null);
151 break;
152 case "pong": //received if we sent a ping (game still alive on our side)
153 {
154 this.oppConnected = true;
155 // Send our "last state" informations to opponent(s)
156 const L = this.game.moves.length;
157 this.st.conn.send(JSON.stringify({
158 code: "lastate",
159 target: this.game.oppid,
160 gameId: this.gameRef.id,
161 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
162 score: this.game.score,
163 movesCount: L,
164 drawOffer: this.drawOffer,
165 clocks: this.game.clocks,
166 }));
167 break;
168 }
169 case "lastate": //got opponent infos about last move
170 {
171 const L = this.game.moves.length;
172 if (this.gameRef.id != data.gameId)
173 break; //games IDs don't match: nothing we can do...
174 // OK, opponent still in game (which might be over)
175 if (data.movesCount > L)
176 {
177 // Just got last move from him
178 this.$refs["basegame"].play(data.lastMove, "receive");
179 if (data.score != "*" && this.game.score == "*")
180 {
181 // Opponent resigned or aborted game, or accepted draw offer
182 // (this is not a stalemate or checkmate)
183 this.$refs["basegame"].endGame(data.score, "Opponent action");
184 }
185 this.game.clocks = data.clocks;
186 this.drawOffer = data.drawOffer;
187 }
188 else if (data.movesCount < L)
189 {
190 // We must tell last move to opponent
191 this.st.conn.send(JSON.stringify({
192 code: "lastate",
193 target: this.game.oppid,
194 gameId: this.gameRef.id,
195 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
196 score: this.game.score,
197 movesCount: L,
198 drawOffer: this.drawOffer,
199 clocks: this.game.clocks,
200 }));
201 }
202 break;
203 }
204 case "resign":
205 this.$refs["basegame"].endGame(
206 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
207 break;
208 case "timeover":
209 this.$refs["basegame"].endGame(
210 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
211 break;
212 case "abort":
213 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
214 break;
215 case "draw":
216 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
217 break;
218 case "drawoffer":
219 this.drawOffer = "received";
220 break;
221 case "askfullgame":
222 // TODO: just give game; observers are listed here anyway:
223 // gameconnect?
224 break;
225 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
226 // ==> on "newmove", check "drawOffer" field
227 // TODO: also use (dis)connect info to count online players?
228 case "gameconnect":
229 case "gamedisconnect":
230 const online = (data.code == "gameconnect");
231 // If this is an opponent ?
232 if (this.game.oppid == data.id)
233 this.oppConnected = true;
234 else
235 {
236 // Or an observer ?
237 if (!online)
238 delete this.people[data.id];
239 else
240 this.people[data.id] = data.name;
241 }
242 break;
243 }
244 },
245 offerDraw: function() {
246 // TODO: also for corr games
247 if (this.drawOffer == "received")
248 {
249 if (!confirm("Accept draw?"))
250 return;
251 this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid}));
252 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
253 }
254 else if (this.drawOffer == "sent")
255 this.drawOffer = "";
256 else
257 {
258 if (!confirm("Offer draw?"))
259 return;
260 this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid}));
261 }
262 },
263 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
264 receiveDrawOffer: function() {
265 //if (...)
266 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
267 // if accept: send message "draw"
268 },
269 abortGame: function(event) {
270 let modalBox = document.getElementById("modalAbort");
271 if (!event)
272 {
273 // First call show options:
274 modalBox.checked = true;
275 }
276 else
277 {
278 modalBox.checked = false; //decision made: box disappear
279 const message = event.target.innerText;
280 // Next line will trigger a "gameover" event, bubbling up till here
281 this.$refs["basegame"].endGame("?", "Abort: " + message);
282 this.st.conn.send(JSON.stringify({
283 code: "abort",
284 msg: message,
285 target: this.game.oppid,
286 }));
287 }
288 },
289 resign: function(e) {
290 if (!confirm("Resign the game?"))
291 return;
292 this.st.conn.send(JSON.stringify({
293 code: "resign",
294 target: this.game.oppid,
295 }));
296 // Next line will trigger a "gameover" event, bubbling up till here
297 this.$refs["basegame"].endGame(
298 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
299 },
300 // 3 cases for loading a game:
301 // - from indexedDB (running or completed live game I play)
302 // - from server (one correspondance game I play[ed] or not)
303 // - from remote peer (one live game I don't play, finished or not)
304 loadGame: function(game) {
305 const afterRetrieval = async (game) => {
306 // NOTE: variants array might not be available yet, thus the two next lines
307 const variantCell = this.st.variants.filter(v => v.id == game.vid);
308 const vname = (variantCell.length > 0 ? variantCell[0].name : "");
309 if (!game.fen)
310 game.fen = game.fenStart; //game wasn't started
311 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
312 if (gtype == "corr")
313 {
314 // corr game: needs to compute the clocks + initime
315 //if (game.players[i].rtime < 0) initime = Date.now(), else compute,
316 //also using move.played fields
317 game.clocks = [-1, -1];
318 game.initime = [0, 0];
319 // TODO: compute clocks + initime
320 }
321 const tc = extractTime(game.timeControl);
322 // TODO: this is not really beautiful (uid on corr players...)
323 if (gtype == "corr" && game.players[0].color == "b")
324 [ game.players[0], game.players[1] ] = [ game.players[1], game.players[0] ];
325 const myIdx = game.players.findIndex(p => {
326 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
327 });
328 if (game.clocks[0] < 0) //game unstarted
329 {
330 game.clocks = [tc.mainTime, tc.mainTime];
331 game.initime[0] = Date.now();
332 if (myIdx >= 0) //I play in this game
333 {
334 GameStorage.update(game.gameId,
335 {
336 clocks: game.clocks,
337 initime: game.initime,
338 });
339 }
340 }
341 const vModule = await import("@/variants/" + vname + ".js");
342 window.V = vModule.VariantRules;
343 this.vr = new V(game.fen);
344 this.game = Object.assign({},
345 game,
346 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
347 {
348 type: gtype,
349 increment: tc.increment,
350 vname: vname,
351 mycolor: [undefined,"w","b"][myIdx+1],
352 // opponent sid not strictly required, but easier
353 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
354 }
355 );
356 if (!!this.game.oppid)
357 {
358 // Send ping to server (answer pong if players[s] are connected)
359 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
360 }
361 };
362 if (!!game)
363 return afterRetrival(game);
364 if (!!this.gameRef.rid)
365 {
366 this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid}));
367 // TODO: just send a game request message to the remote player,
368 // and when receiving answer just call loadGame(received_game)
369 // + remote peer should have registered us as an observer
370 // (send moves updates + resign/abort/draw actions)
371 }
372 else
373 {
374 GameStorage.get(this.gameRef.id, async (game) => {
375 afterRetrieval(game);
376 });
377 }
378 },
379 // Post-process a move (which was just played)
380 processMove: function(move) {
381 if (!this.game.mycolor)
382 return; //I'm just an observer
383 // Update storage (corr or live)
384 const colorIdx = ["w","b"].indexOf(move.color);
385 // https://stackoverflow.com/a/38750895
386 const allowed_fields = ["appear", "vanish", "start", "end"];
387 const filtered_move = Object.keys(move)
388 .filter(key => allowed_fields.includes(key))
389 .reduce((obj, key) => {
390 obj[key] = move[key];
391 return obj;
392 }, {});
393 // Send move ("newmove" event) to opponent(s) (if ours)
394 let addTime = 0;
395 if (move.color == this.game.mycolor)
396 {
397 if (this.game.moves.length >= 2) //after first move
398 {
399 const elapsed = Date.now() - this.game.initime[colorIdx];
400 // elapsed time is measured in milliseconds
401 addTime = this.game.increment - elapsed/1000;
402 }
403 this.st.conn.send(JSON.stringify({
404 code: "newmove",
405 target: this.game.oppid,
406 move: Object.assign({}, filtered_move, {addTime: addTime}),
407 }));
408 }
409 else
410 addTime = move.addTime; //supposed transmitted
411 const nextIdx = ["w","b"].indexOf(this.vr.turn);
412 GameStorage.update(this.gameRef.id,
413 {
414 move: filtered_move,
415 fen: move.fen,
416 clocks: this.game.clocks.map((t,i) => i==colorIdx
417 ? this.game.clocks[i] + addTime
418 : this.game.clocks[i]),
419 initime: this.game.initime.map((t,i) => i==nextIdx
420 ? Date.now()
421 : this.game.initime[i]),
422 });
423 // Also update current game object:
424 this.game.moves.push(move);
425 this.game.fen = move.fen;
426 //TODO: just this.game.clocks[colorIdx] += addTime;
427 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
428 this.game.initime[nextIdx] = Date.now();
429 },
430 // TODO: this update function should also work for corr games
431 gameOver: function(score) {
432 this.game.mode = "analyze";
433 GameStorage.update(this.gameRef.id, { score: score });
434 },
435 },
436 };
437 </script>
438
439 <style lang="sass">
440 // TODO
441 </style>