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