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