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