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