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