Advance on draw logic (for live, not corr)
[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 case "duplicate":
128 alert("Warning: duplicate 'offline' connection");
129 break;
130 // 0.2] Receive clients list (just socket IDs)
131 case "pollclients":
132 {
133 data.sockIds.forEach(sid => {
134 this.people.push({sid:sid, id:0, name:""});
135 // Ask only identity
136 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
137 });
138 break;
139 }
140 case "askidentity":
141 {
142 // Request for identification: reply if I'm not anonymous
143 if (this.st.user.id > 0)
144 {
145 this.st.conn.send(JSON.stringify(
146 // people[0] instead of st.user to avoid sending email
147 {code:"identity", user:this.people[0], target:data.from}));
148 }
149 break;
150 }
151 case "identity":
152 {
153 let player = this.people.find(p => p.sid == data.user.sid);
154 // NOTE: sometimes player.id fails because player is undefined...
155 // Probably because the event was meant for Hall?
156 if (!player)
157 return;
158 player.id = data.user.id;
159 player.name = data.user.name;
160 // Sending last state only for live games: corr games are complete
161 if (this.game.type == "live" && this.game.oppsid == player.sid)
162 {
163 // Send our "last state" informations to opponent
164 const L = this.game.moves.length;
165 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
166 if (!!lastMove && this.drawOffer == "sent")
167 lastMove.draw = true;
168 this.st.conn.send(JSON.stringify({
169 code: "lastate",
170 target: player.sid,
171 state:
172 {
173 lastMove: lastMove,
174 score: this.game.score,
175 movesCount: L,
176 clocks: this.game.clocks,
177 }
178 }));
179 }
180 break;
181 }
182 case "askgame":
183 // Send current (live) game
184 const myGame =
185 {
186 // Minimal game informations:
187 id: this.game.id,
188 players: this.game.players.map(p => { return {name:p.name}; }),
189 vid: this.game.vid,
190 timeControl: this.game.timeControl,
191 };
192 this.st.conn.send(JSON.stringify({code:"game",
193 game:myGame, target:data.from}));
194 break;
195 case "newmove":
196 // NOTE: this call to play() will trigger processMove()
197 this.$refs["basegame"].play(data.move,
198 "receive", this.game.vname!="Dark" ? "animate" : null);
199 break;
200 case "lastate": //got opponent infos about last move
201 {
202 const L = this.game.moves.length;
203 if (data.movesCount > L)
204 {
205 // Just got last move from him
206 this.$refs["basegame"].play(data.lastMove,
207 "receive", this.game.vname!="Dark" ? "animate" : null);
208 if (data.score != "*" && this.game.score == "*")
209 {
210 // Opponent resigned or aborted game, or accepted draw offer
211 // (this is not a stalemate or checkmate)
212 this.$refs["basegame"].endGame(data.score, "Opponent action");
213 }
214 this.game.clocks = data.clocks; //TODO: check this?
215 if (!!data.lastMove.draw)
216 this.drawOffer = "received";
217 }
218 break;
219 }
220 case "resign":
221 this.$refs["basegame"].endGame(
222 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
223 break;
224 case "abort":
225 this.$refs["basegame"].endGame("?", "Abort");
226 break;
227 case "draw":
228 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
229 break;
230 case "drawoffer":
231 this.drawOffer = "received";
232 break;
233 case "drawaccepted":
234 this.gameOver("1/2");
235 break;
236 case "askfullgame":
237 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
238 break;
239 case "fullgame":
240 this.loadGame(data.game);
241 break;
242 case "connect":
243 {
244 this.people.push({name:"", id:0, sid:data.from});
245 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
246 break;
247 }
248 case "disconnect":
249 ArrayFun.remove(this.people, p => p.sid == data.from);
250 break;
251 }
252 },
253 offerDraw: function() {
254 // TODO: also for corr games
255 if (this.drawOffer == "received")
256 {
257 if (!confirm("Accept draw?"))
258 return;
259 const oppsid = this.getOppSid(); //TODO: to all people...
260 if (!!oppsid)
261 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
262 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
263 }
264 else if (this.drawOffer == "sent")
265 this.drawOffer = "";
266 else
267 {
268 if (!confirm("Offer draw?"))
269 return;
270 const oppsid = this.getOppSid();
271 if (!!oppsid)
272 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
273 }
274 },
275 abortGame: function() {
276 if (!confirm(this.st.tr["Terminate game?"]))
277 return;
278 // Next line will trigger a "gameover" event, bubbling up till here
279 this.$refs["basegame"].endGame("?", "Abort");
280 this.people.forEach(p => {
281 if (p.sid != this.st.user.sid)
282 {
283 this.st.conn.send(JSON.stringify({
284 code: "abort",
285 target: p.sid,
286 }));
287 }
288 });
289 },
290 resign: function(e) {
291 if (!confirm("Resign the game?"))
292 return;
293 const oppsid = this.getOppSid();
294 if (!!oppsid)
295 {
296 this.st.conn.send(JSON.stringify({
297 code: "resign",
298 target: oppsid,
299 }));
300 }
301 // Next line will trigger a "gameover" event, bubbling up till here
302 this.$refs["basegame"].endGame(
303 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
304 },
305 // 3 cases for loading a game:
306 // - from indexedDB (running or completed live game I play)
307 // - from server (one correspondance game I play[ed] or not)
308 // - from remote peer (one live game I don't play, finished or not)
309 loadGame: function(game) {
310 const afterRetrieval = async (game) => {
311 const vModule = await import("@/variants/" + game.vname + ".js");
312 window.V = vModule.VariantRules;
313 this.vr = new V(game.fen);
314 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
315 const tc = extractTime(game.timeControl);
316 if (gtype == "corr")
317 {
318 if (game.players[0].color == "b")
319 {
320 // Adopt the same convention for live and corr games: [0] = white
321 [ game.players[0], game.players[1] ] =
322 [ game.players[1], game.players[0] ];
323 }
324 // corr game: needs to compute the clocks + initime
325 // NOTE: clocks in seconds, initime in milliseconds
326 game.clocks = [tc.mainTime, tc.mainTime];
327 game.initime = [0, 0];
328 const L = game.moves.length;
329 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
330 if (L >= 3)
331 {
332 let addTime = [0, 0];
333 for (let i=2; i<L; i++)
334 {
335 addTime[i%2] += tc.increment -
336 (game.moves[i].played - game.moves[i-1].played) / 1000;
337 }
338 for (let i=0; i<=1; i++)
339 game.clocks[i] += addTime[i];
340 }
341 if (L >= 1)
342 game.initime[L%2] = game.moves[L-1].played;
343 // Now that we used idx and played, re-format moves as for live games
344 game.moves = game.moves.map( (m) => {
345 const s = m.squares;
346 return {
347 appear: s.appear,
348 vanish: s.vanish,
349 start: s.start,
350 end: s.end,
351 message: m.message,
352 };
353 });
354 }
355 const myIdx = game.players.findIndex(p => {
356 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
357 });
358 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
359 {
360 game.clocks = [tc.mainTime, tc.mainTime];
361 game.initime[0] = Date.now();
362 if (myIdx >= 0)
363 {
364 // I play in this live game; corr games don't have clocks+initime
365 GameStorage.update(game.id,
366 {
367 clocks: game.clocks,
368 initime: game.initime,
369 });
370 }
371 }
372 this.game = Object.assign({},
373 game,
374 // NOTE: assign mycolor here, since BaseGame could also be VS computer
375 {
376 type: gtype,
377 increment: tc.increment,
378 mycolor: [undefined,"w","b"][myIdx+1],
379 // opponent sid not strictly required (or available), but easier
380 // at least oppsid or oppid is available anyway:
381 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
382 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
383 }
384 );
385 };
386 if (!!game)
387 return afterRetrieval(game);
388 if (!!this.gameRef.rid)
389 {
390 // Remote live game
391 // (TODO: send game ID as well, and receiver would pick the corresponding
392 // game in his current games; if allowed to play several)
393 this.st.conn.send(JSON.stringify(
394 {code:"askfullgame", target:this.gameRef.rid}));
395 // (send moves updates + resign/abort/draw actions)
396 }
397 else
398 {
399 // Local or corr game
400 GameStorage.get(this.gameRef.id, afterRetrieval);
401 }
402 },
403 // Post-process a move (which was just played)
404 processMove: function(move) {
405 if (!this.game.mycolor)
406 return; //I'm just an observer
407 // Update storage (corr or live)
408 const colorIdx = ["w","b"].indexOf(move.color);
409 // https://stackoverflow.com/a/38750895
410 const allowed_fields = ["appear", "vanish", "start", "end"];
411 const filtered_move = Object.keys(move)
412 .filter(key => allowed_fields.includes(key))
413 .reduce((obj, key) => {
414 obj[key] = move[key];
415 return obj;
416 }, {});
417 // Send move ("newmove" event) to people in the room (if our turn)
418 let addTime = 0;
419 if (move.color == this.game.mycolor)
420 {
421 if (this.game.moves.length >= 2) //after first move
422 {
423 const elapsed = Date.now() - this.game.initime[colorIdx];
424 // elapsed time is measured in milliseconds
425 addTime = this.game.increment - elapsed/1000;
426 }
427 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
428 if (this.game.type == "corr")
429 sendMove.message = this.corrMsg;
430 const oppsid = this.getOppSid();
431 this.people.forEach(p => {
432 if (p.sid != this.st.user.sid)
433 {
434 this.st.conn.send(JSON.stringify({
435 code: "newmove",
436 target: p.sid,
437 move: sendMove,
438 }));
439 }
440 });
441 if (this.game.type == "corr" && this.corrMsg != "")
442 {
443 // Add message to last move in BaseGame:
444 // TODO: not very good style...
445 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
446 }
447 }
448 else
449 addTime = move.addTime; //supposed transmitted
450 const nextIdx = ["w","b"].indexOf(this.vr.turn);
451 // Since corr games are stored at only one location, update should be
452 // done only by one player for each move:
453 if (this.game.type == "live" || move.color == this.game.mycolor)
454 {
455 if (this.game.type == "corr")
456 {
457 GameStorage.update(this.gameRef.id,
458 {
459 fen: move.fen,
460 move:
461 {
462 squares: filtered_move,
463 message: this.corrMsg,
464 played: Date.now(), //TODO: on server?
465 idx: this.game.moves.length,
466 },
467 });
468 }
469 else //live
470 {
471 GameStorage.update(this.gameRef.id,
472 {
473 fen: move.fen,
474 move: filtered_move,
475 clocks: this.game.clocks.map((t,i) => i==colorIdx
476 ? this.game.clocks[i] + addTime
477 : this.game.clocks[i]),
478 initime: this.game.initime.map((t,i) => i==nextIdx
479 ? Date.now()
480 : this.game.initime[i]),
481 });
482 }
483 }
484 // Also update current game object:
485 this.game.moves.push(move);
486 this.game.fen = move.fen;
487 //TODO: just this.game.clocks[colorIdx] += addTime;
488 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
489 this.game.initime[nextIdx] = Date.now();
490 // Finally reset curMoveMessage if needed
491 if (this.game.type == "corr" && move.color == this.game.mycolor)
492 this.corrMsg = "";
493 },
494 gameOver: function(score) {
495 this.game.mode = "analyze";
496 this.game.score = score;
497 const myIdx = this.game.players.findIndex(p => {
498 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
499 });
500 if (myIdx >= 0) //OK, I play in this game
501 GameStorage.update(this.gameRef.id, { score: score });
502 },
503 },
504 };
505 </script>
506
507 <style lang="sass">
508 // TODO
509 </style>