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