Work on sizes, CSS
[vchess.git] / client / src / views / Game.vue
CommitLineData
a6088c90 1<template lang="pug">
7aa548e7 2main
a1c48034
BA
3 input#modalChat.modal(type="checkbox" @change="toggleChat")
4 div(role="dialog" aria-labelledby="inputChat")
5 #chat.card
6 label.modal-close(for="modalChat")
3837d4f7 7 Chat(:players="game.players" :pastChats="game.chats"
a1c48034 8 @newchat-sent="finishSendChat" @newchat-received="processChat")
7aa548e7 9 .row
a1c48034 10 .col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
cf94b843 11 button#chatBtn(onClick="doClick('modalChat')") Chat
430a2038 12 #actions(v-if="game.mode!='analyze' && game.score=='*'")
7aa548e7
BA
13 button(@click="offerDraw") Draw
14 button(@click="abortGame") Abort
15 button(@click="resign") Resign
16 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
17 div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
430a2038
BA
18 BaseGame(:game="game" :vr="vr" ref="basegame"
19 @newmove="processMove" @gameover="gameOver")
a6088c90
BA
20</template>
21
22<script>
46284a2f 23import BaseGame from "@/components/BaseGame.vue";
f21cd6d9 24import Chat from "@/components/Chat.vue";
a6088c90 25import { store } from "@/store";
967a2686 26import { GameStorage } from "@/utils/gameStorage";
5b87454c 27import { ppt } from "@/utils/datetime";
66d03f23 28import { extractTime } from "@/utils/timeControl";
f41ce580 29import { ArrayFun } from "@/utils/array";
a6088c90
BA
30
31export default {
32 name: 'my-game',
33 components: {
34 BaseGame,
5c8e044f 35 Chat,
a6088c90 36 },
f7121527 37 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
38 data: function() {
39 return {
40 st: store.state,
4b0384fa
BA
41 gameRef: { //given in URL (rid = remote ID)
42 id: "",
43 rid: ""
44 },
f41ce580 45 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
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)
430a2038 82 this.gameOver(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":
06e79b07 202 this.$set(this.game, "moveToPlay", data.move); //TODO: Vue3...
f41ce580 203 break;
a6088c90 204 case "lastate": //got opponent infos about last move
6fba6e0c 205 {
760adbce
BA
206 this.lastate = data;
207 if (!!this.game.type) //game is loaded
208 this.processLastate();
209 //else: will be processed when game is ready
a6088c90 210 break;
6fba6e0c 211 }
93d1d7a7 212 case "resign":
430a2038 213 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
93d1d7a7 214 break;
93d1d7a7 215 case "abort":
430a2038 216 this.gameOver("?", "Abort");
93d1d7a7 217 break;
2cc10cdb 218 case "draw":
430a2038 219 this.gameOver("1/2", "Mutual agreement");
2cc10cdb
BA
220 break;
221 case "drawoffer":
760adbce 222 this.drawOffer = "received"; //TODO: observers don't know who offered draw
6d9f4315 223 break;
7e1a1fe9 224 case "askfullgame":
dc284d90 225 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
7e1a1fe9 226 break;
5f131484 227 case "fullgame":
760adbce
BA
228 // Callback "roomInit" to poll clients only after game is loaded
229 this.loadGame(data.game, this.roomInit);
5f131484 230 break;
5f131484
BA
231 case "connect":
232 {
c6788ecf
BA
233 this.people.push({name:"", id:0, sid:data.from});
234 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
5f131484
BA
235 break;
236 }
237 case "disconnect":
c6788ecf 238 ArrayFun.remove(this.people, p => p.sid == data.from);
a6088c90
BA
239 break;
240 }
cdb34c93 241 },
760adbce
BA
242 // lastate was received, but maybe game wasn't ready yet:
243 processLastate: function() {
244 const data = this.lastate;
245 this.lastate = undefined; //security...
246 const L = this.game.moves.length;
247 if (data.movesCount > L)
248 {
249 // Just got last move from him
06e79b07 250 this.$set(this.game, "moveToPlay", data.lastMove);
760adbce
BA
251 if (data.score != "*" && this.game.score == "*")
252 {
253 // Opponent resigned or aborted game, or accepted draw offer
254 // (this is not a stalemate or checkmate)
430a2038 255 this.gameOver(data.score, "Opponent action");
760adbce
BA
256 }
257 this.game.clocks = data.clocks; //TODO: check this?
258 if (!!data.lastMove.draw)
259 this.drawOffer = "received";
260 }
261 },
a6088c90 262 offerDraw: function() {
a1c48034 263 if (["received","threerep"].includes(this.drawOffer))
6fba6e0c 264 {
2cc10cdb 265 if (!confirm("Accept draw?"))
6fba6e0c 266 return;
760adbce
BA
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 });
a1c48034
BA
271 const message = (this.drawOffer == "received"
272 ? "Mutual agreement"
273 : "Three repetitions");
274 this.gameOver("1/2", message);
2cc10cdb 275 }
6fba6e0c 276 else if (this.drawOffer == "sent")
b7cbbda1 277 {
6fba6e0c 278 this.drawOffer = "";
b7cbbda1
BA
279 if (this.game.type == "corr")
280 GameStorage.update(this.gameRef.id, {drawOffer: false});
281 }
6fba6e0c
BA
282 else
283 {
284 if (!confirm("Offer draw?"))
285 return;
760adbce
BA
286 this.drawOffer = "sent";
287 this.people.forEach(p => {
288 if (p.sid != this.st.user.sid)
289 this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid}));
290 });
b7cbbda1
BA
291 if (this.game.type == "corr")
292 GameStorage.update(this.gameRef.id, {drawOffer: true});
a6088c90
BA
293 }
294 },
7f3484bd
BA
295 abortGame: function() {
296 if (!confirm(this.st.tr["Terminate game?"]))
297 return;
430a2038 298 this.gameOver("?", "Abort");
7f3484bd
BA
299 this.people.forEach(p => {
300 if (p.sid != this.st.user.sid)
5f131484
BA
301 {
302 this.st.conn.send(JSON.stringify({
303 code: "abort",
7f3484bd 304 target: p.sid,
5f131484
BA
305 }));
306 }
7f3484bd 307 });
a6088c90
BA
308 },
309 resign: function(e) {
310 if (!confirm("Resign the game?"))
311 return;
760adbce
BA
312 this.people.forEach(p => {
313 if (p.sid != this.st.user.sid)
314 {
315 this.st.conn.send(JSON.stringify({code:"resign",
316 side:this.game.mycolor, target:p.sid}));
317 }
318 });
430a2038 319 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 320 },
967a2686
BA
321 // 3 cases for loading a game:
322 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
323 // - from server (one correspondance game I play[ed] or not)
324 // - from remote peer (one live game I don't play, finished or not)
760adbce 325 loadGame: function(game, callback) {
967a2686 326 const afterRetrieval = async (game) => {
f41ce580
BA
327 const vModule = await import("@/variants/" + game.vname + ".js");
328 window.V = vModule.VariantRules;
329 this.vr = new V(game.fen);
c0b27606 330 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
92a523d1 331 const tc = extractTime(game.timeControl);
c0b27606
BA
332 if (gtype == "corr")
333 {
f41ce580
BA
334 if (game.players[0].color == "b")
335 {
336 // Adopt the same convention for live and corr games: [0] = white
337 [ game.players[0], game.players[1] ] =
338 [ game.players[1], game.players[0] ];
339 }
c0b27606 340 // corr game: needs to compute the clocks + initime
7f3484bd 341 // NOTE: clocks in seconds, initime in milliseconds
92a523d1 342 game.clocks = [tc.mainTime, tc.mainTime];
92b82def 343 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
b7cbbda1 344 if (game.score == "*") //otherwise no need to bother with time
92a523d1 345 {
b7cbbda1
BA
346 game.initime = [0, 0];
347 const L = game.moves.length;
348 if (L >= 3)
5f131484 349 {
b7cbbda1
BA
350 let addTime = [0, 0];
351 for (let i=2; i<L; i++)
352 {
353 addTime[i%2] += tc.increment -
354 (game.moves[i].played - game.moves[i-1].played) / 1000;
355 }
356 for (let i=0; i<=1; i++)
357 game.clocks[i] += addTime[i];
5f131484 358 }
b7cbbda1
BA
359 if (L >= 1)
360 game.initime[L%2] = game.moves[L-1].played;
361 if (game.drawOffer)
362 this.drawOffer = "received";
92a523d1 363 }
92b82def 364 // Now that we used idx and played, re-format moves as for live games
6d68309a 365 game.moves = game.moves.map( (m) => {
92b82def 366 const s = m.squares;
6d68309a 367 return {
92b82def
BA
368 appear: s.appear,
369 vanish: s.vanish,
370 start: s.start,
371 end: s.end,
92b82def
BA
372 };
373 });
3837d4f7
BA
374 // Also sort chat messages (if any)
375 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
c0b27606 376 }
f41ce580
BA
377 const myIdx = game.players.findIndex(p => {
378 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
379 });
92a523d1 380 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
66d03f23
BA
381 {
382 game.clocks = [tc.mainTime, tc.mainTime];
b7cbbda1 383 if (game.score == "*")
22efa391 384 {
b7cbbda1
BA
385 game.initime[0] = Date.now();
386 if (myIdx >= 0)
22efa391 387 {
b7cbbda1
BA
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 }
22efa391 395 }
66d03f23 396 }
4b0384fa
BA
397 this.game = Object.assign({},
398 game,
cf742aaf 399 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 400 {
c0b27606 401 type: gtype,
66d03f23 402 increment: tc.increment,
6fba6e0c 403 mycolor: [undefined,"w","b"][myIdx+1],
5f131484
BA
404 // opponent sid not strictly required (or available), but easier
405 // at least oppsid or oppid is available anyway:
406 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
407 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
6fba6e0c 408 }
4b0384fa 409 );
72ccbd67 410 this.repeat = {}; //reset
760adbce
BA
411 if (!!this.lastate) //lastate arrived before game was loaded:
412 this.processLastate();
413 callback();
967a2686
BA
414 };
415 if (!!game)
dc284d90 416 return afterRetrieval(game);
967a2686
BA
417 if (!!this.gameRef.rid)
418 {
760adbce 419 // Remote live game: forgetting about callback func... (TODO: design)
5f131484
BA
420 this.st.conn.send(JSON.stringify(
421 {code:"askfullgame", target:this.gameRef.rid}));
967a2686
BA
422 }
423 else
424 {
f41ce580 425 // Local or corr game
11667c79 426 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 427 }
a6088c90 428 },
9d54ab89 429 // Post-process a move (which was just played)
ce87ac6a 430 processMove: function(move) {
a1c48034 431 // Update storage (corr or live) if I play in the game
6fba6e0c 432 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89 433 // https://stackoverflow.com/a/38750895
a1c48034
BA
434 if (!!this.game.mycolor)
435 {
436 const allowed_fields = ["appear", "vanish", "start", "end"];
437 // NOTE: 'var' to see this variable outside this block
438 var filtered_move = Object.keys(move)
439 .filter(key => allowed_fields.includes(key))
440 .reduce((obj, key) => {
441 obj[key] = move[key];
442 return obj;
443 }, {});
444 }
dc284d90 445 // Send move ("newmove" event) to people in the room (if our turn)
dce792f6 446 let addTime = 0;
9d54ab89 447 if (move.color == this.game.mycolor)
b4fb1612 448 {
dce792f6
BA
449 if (this.game.moves.length >= 2) //after first move
450 {
451 const elapsed = Date.now() - this.game.initime[colorIdx];
452 // elapsed time is measured in milliseconds
453 addTime = this.game.increment - elapsed/1000;
454 }
6d68309a 455 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
dc284d90
BA
456 this.people.forEach(p => {
457 if (p.sid != this.st.user.sid)
458 {
459 this.st.conn.send(JSON.stringify({
460 code: "newmove",
461 target: p.sid,
462 move: sendMove,
463 }));
464 }
465 });
b4fb1612 466 }
5b87454c
BA
467 else
468 addTime = move.addTime; //supposed transmitted
6fba6e0c 469 const nextIdx = ["w","b"].indexOf(this.vr.turn);
6d68309a
BA
470 // Since corr games are stored at only one location, update should be
471 // done only by one player for each move:
a1c48034
BA
472 if (!!this.game.mycolor &&
473 (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
BA
479 fen: move.fen,
480 move:
481 {
482 squares: filtered_move,
e69f159d
BA
483 played: Date.now(), //TODO: on server?
484 idx: this.game.moves.length,
485 },
486 });
487 }
488 else //live
489 {
490 GameStorage.update(this.gameRef.id,
491 {
492 fen: move.fen,
493 move: filtered_move,
494 clocks: this.game.clocks.map((t,i) => i==colorIdx
495 ? this.game.clocks[i] + addTime
496 : this.game.clocks[i]),
497 initime: this.game.initime.map((t,i) => i==nextIdx
498 ? Date.now()
499 : this.game.initime[i]),
500 });
501 }
6d68309a 502 }
967a2686
BA
503 // Also update current game object:
504 this.game.moves.push(move);
505 this.game.fen = move.fen;
760adbce 506 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
66d03f23 507 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
809ba2aa 508 this.game.initime[nextIdx] = Date.now();
72ccbd67
BA
509 // If repetition detected, consider that a draw offer was received:
510 const fenObj = V.ParseFen(move.fen);
511 let repIdx = fenObj.position + "_" + fenObj.turn;
512 if (!!fenObj.flags)
513 repIdx += "_" + fenObj.flags;
514 this.repeat[repIdx] = (!!this.repeat[repIdx]
515 ? this.repeat[repIdx]+1
516 : 1);
517 if (this.repeat[repIdx] >= 3)
a1c48034 518 this.drawOffer = "threerep";
b4fb1612 519 },
a1c48034
BA
520 toggleChat: function() {
521 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
522 },
523 finishSendChat: function(chat) {
63ca2b89
BA
524 if (this.game.type == "corr")
525 GameStorage.update(this.gameRef.id, {chat: chat});
526 },
a1c48034
BA
527 processChat: function() {
528 if (!document.getElementById("inputChat").checked)
529 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
530 },
430a2038 531 gameOver: function(score, scoreMsg) {
93d1d7a7 532 this.game.mode = "analyze";
430a2038
BA
533 this.game.score = score;
534 this.game.scoreMsg = scoreMsg;
ab6f48ea
BA
535 const myIdx = this.game.players.findIndex(p => {
536 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
537 });
538 if (myIdx >= 0) //OK, I play in this game
539 GameStorage.update(this.gameRef.id, { score: score });
ce87ac6a 540 },
a6088c90
BA
541 },
542};
543</script>
7e1a1fe9
BA
544
545<style lang="sass">
72ccbd67
BA
546.connected
547 background-color: green
72ccbd67
BA
548.disconnected
549 background-color: red
550
430a2038
BA
551@media screen and (min-width: 768px)
552 #actions
553 width: 300px
554@media screen and (max-width: 767px)
555 .game
556 width: 100%
72ccbd67 557
430a2038 558#actions
cf94b843 559 display: inline-block
430a2038 560 margin-top: 10px
430a2038
BA
561 button
562 display: inline-block
563 width: 33%
564 margin: 0
a1c48034 565
430a2038 566#chat
a1c48034
BA
567 padding-top: 20px
568 max-width: 600px
430a2038 569 border: none;
cf94b843
BA
570
571#chatBtn
572 margin: 0 10px 0 0
7e1a1fe9 573</style>