Experimental improved behavior of login/logout/multitabs
[vchess.git] / client / src / views / Game.vue
CommitLineData
a6088c90 1<template lang="pug">
7aa548e7 2main
bfe9a135 3 input#modalChat.modal(type="checkbox" @click="resetChatColor")
602d6bef 4 div#chatWrap(role="dialog" data-checkbox="modalChat" aria-labelledby="inputChat")
a1c48034
BA
5 #chat.card
6 label.modal-close(for="modalChat")
ed06d9e9 7 #participants
ac8f441c 8 span {{ Object.keys(people).length + " " + st.tr["participant(s):"] }}
ed06d9e9
BA
9 span(v-for="p in Object.values(people)" v-if="!!p.name")
10 | {{ p.name }}
11 span.anonymous(v-if="Object.values(people).some(p => !p.name)")
12 | + @nonymous
3837d4f7 13 Chat(:players="game.players" :pastChats="game.chats"
ac8f441c 14 :newChat="newChat" @mychat="processChat")
7aa548e7 15 .row
050ae3b5 16 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
8c5f5390 17 span.variant-info {{ game.vname }}
cf94b843 18 button#chatBtn(onClick="doClick('modalChat')") Chat
4f518610 19 #actions(v-if="game.score=='*'")
602d6bef
BA
20 button(@click="clickDraw" :class="{['draw-' + drawOffer]: true}")
21 | {{ st.tr["Draw"] }}
77c50966
BA
22 button(v-if="!!game.mycolor" @click="abortGame") {{ st.tr["Abort"] }}
23 button(v-if="!!game.mycolor" @click="resign") {{ st.tr["Resign"] }}
050ae3b5
BA
24 #playersInfo
25 p
5bcc9b31
BA
26 span.name(:class="{connected: isConnected(0)}")
27 | {{ game.players[0].name || "@nonymous" }}
050ae3b5
BA
28 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
29 span.split-names -
5bcc9b31
BA
30 span.name(:class="{connected: isConnected(1)}")
31 | {{ game.players[1].name || "@nonymous" }}
050ae3b5 32 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
430a2038
BA
33 BaseGame(:game="game" :vr="vr" ref="basegame"
34 @newmove="processMove" @gameover="gameOver")
a6088c90
BA
35</template>
36
37<script>
46284a2f 38import BaseGame from "@/components/BaseGame.vue";
f21cd6d9 39import Chat from "@/components/Chat.vue";
a6088c90 40import { store } from "@/store";
967a2686 41import { GameStorage } from "@/utils/gameStorage";
5b87454c 42import { ppt } from "@/utils/datetime";
66d03f23 43import { extractTime } from "@/utils/timeControl";
f41ce580 44import { ArrayFun } from "@/utils/array";
dcd68c41 45import { processModalClick } from "@/utils/modalClick";
77c50966 46import { getScoreMessage } from "@/utils/scoring";
a6088c90
BA
47
48export default {
49 name: 'my-game',
50 components: {
51 BaseGame,
5c8e044f 52 Chat,
a6088c90 53 },
f7121527 54 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
55 data: function() {
56 return {
57 st: store.state,
4b0384fa
BA
58 gameRef: { //given in URL (rid = remote ID)
59 id: "",
60 rid: ""
61 },
a0c41e7e
BA
62 game: { //passed to BaseGame
63 players:[{name:""},{name:""}],
64 rendered: false,
65 },
809ba2aa 66 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 67 vr: null, //"variant rules" object initialized from FEN
dcd68c41
BA
68 drawOffer: "",
69 people: {}, //players + observers
760adbce 70 lastate: undefined, //used if opponent send lastate before game is ready
72ccbd67 71 repeat: {}, //detect position repetition
ac8f441c 72 newChat: "",
a6088c90
BA
73 };
74 },
75 watch: {
5f131484
BA
76 "$route": function(to, from) {
77 this.gameRef.id = to.params["id"];
78 this.gameRef.rid = to.query["rid"];
79 this.loadGame();
a6088c90 80 },
5b87454c 81 "game.clocks": function(newState) {
b7cbbda1 82 if (this.game.moves.length < 2 || this.game.score != "*")
dce792f6 83 {
b7cbbda1 84 // 1st move not completed yet, or game over: freeze time
dce792f6
BA
85 this.virtualClocks = newState.map(s => ppt(s));
86 return;
87 }
809ba2aa 88 const currentTurn = this.vr.turn;
6fba6e0c 89 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
90 let countdown = newState[colorIdx] -
91 (Date.now() - this.game.initime[colorIdx])/1000;
c0b27606
BA
92 this.virtualClocks = [0,1].map(i => {
93 const removeTime = i == colorIdx
94 ? (Date.now() - this.game.initime[colorIdx])/1000
95 : 0;
96 return ppt(newState[i] - removeTime);
97 });
809ba2aa 98 let clockUpdate = setInterval(() => {
e69f159d 99 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
809ba2aa
BA
100 {
101 clearInterval(clockUpdate);
e69f159d 102 if (countdown < 0)
602d6bef 103 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
809ba2aa 104 }
9aa229f3 105 else
9aa229f3 106 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
809ba2aa 107 }, 1000);
5b87454c 108 },
92a523d1 109 },
dcd68c41 110 // NOTE: some redundant code with Hall.vue (related to people array)
a6088c90 111 created: function() {
5f131484
BA
112 // Always add myself to players' list
113 const my = this.st.user;
dcd68c41 114 this.$set(this.people, my.sid, {id:my.id, name:my.name});
dc284d90
BA
115 this.gameRef.id = this.$route.params["id"];
116 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
760adbce 117 // Define socket .onmessage() and .onclose() events:
5f131484 118 this.st.conn.onmessage = this.socketMessageListener;
cdb34c93
BA
119 const socketCloseListener = () => {
120 store.socketCloseListener(); //reinitialize connexion (in store.js)
a9b131f1 121 this.st.conn.addEventListener('message', this.socketMessageListener);
cdb34c93
BA
122 this.st.conn.addEventListener('close', socketCloseListener);
123 };
cdb34c93 124 this.st.conn.onclose = socketCloseListener;
760adbce
BA
125 // Socket init required before loading remote game:
126 const socketInit = (callback) => {
127 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
128 callback();
129 else //socket not ready yet (initial loading)
130 this.st.conn.onopen = callback;
131 };
132 if (!this.gameRef.rid) //game stored locally or on server
133 this.loadGame(null, () => socketInit(this.roomInit));
134 else //game stored remotely: need socket to retrieve it
135 {
136 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
137 // --> It will be given when receiving "fullgame" socket event.
138 // A more general approach would be to store it somewhere.
139 socketInit(this.loadGame);
140 }
cdb34c93 141 },
dcd68c41
BA
142 mounted: function() {
143 document.getElementById("chatWrap").addEventListener(
144 "click", processModalClick);
145 },
cdb34c93 146 methods: {
760adbce
BA
147 // O.1] Ask server for room composition:
148 roomInit: function() {
41c80bb6
BA
149 // Notify the room only now that I connected, because
150 // messages might be lost otherwise (if game loading is slow)
151 this.st.conn.send(JSON.stringify({code:"connect"}));
760adbce 152 this.st.conn.send(JSON.stringify({code:"pollclients"}));
5f131484 153 },
050ae3b5 154 isConnected: function(index) {
29ced362
BA
155 const player = this.game.players[index];
156 // Is it me ?
157 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
050ae3b5 158 return true;
29ced362
BA
159 // Try to find a match in people:
160 return Object.keys(this.people).some(sid => sid == player.sid) ||
161 Object.values(this.people).some(p => p.id == player.uid);
050ae3b5 162 },
cdb34c93 163 socketMessageListener: function(msg) {
a6088c90 164 const data = JSON.parse(msg.data);
a6088c90
BA
165 switch (data.code)
166 {
6d9f4315 167 case "duplicate":
a3ac374b 168 this.st.conn.send(JSON.stringify({code:"duplicate"}));
602d6bef 169 alert(this.st.tr["Warning: multi-tabs not supported"]);
6d9f4315 170 break;
5f131484
BA
171 // 0.2] Receive clients list (just socket IDs)
172 case "pollclients":
5f131484 173 data.sockIds.forEach(sid => {
dcd68c41
BA
174 if (!!this.people[sid])
175 return;
176 this.$set(this.people, sid, {id:0, name:""});
5f131484
BA
177 // Ask only identity
178 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
179 });
180 break;
5f131484 181 case "askidentity":
5f131484
BA
182 // Request for identification: reply if I'm not anonymous
183 if (this.st.user.id > 0)
184 {
dcd68c41
BA
185 this.st.conn.send(JSON.stringify({code:"identity",
186 user: {
187 // NOTE: decompose to avoid revealing email
188 name: this.st.user.name,
189 sid: this.st.user.sid,
190 id: this.st.user.id,
191 },
192 target:data.from}));
5f131484
BA
193 }
194 break;
5f131484 195 case "identity":
41c80bb6
BA
196 this.$set(this.people, data.user.sid,
197 {id: data.user.id, name: data.user.name});
a0c41e7e
BA
198 // Ask potentially missed last state, if opponent and I play
199 if (!!this.game.mycolor
200 && this.game.type == "live" && this.game.score == "*"
201 && this.game.players.some(p => p.sid == data.user.sid))
202 {
203 this.st.conn.send(JSON.stringify({code:"asklastate", target:data.user.sid}));
204 }
205 break;
a0c41e7e 206 case "asklastate":
a0c41e7e
BA
207 // Sending last state if I played a move or score != "*"
208 if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
633959bf 209 || this.game.score != "*" || this.drawOffer == "sent")
411d23cd 210 {
f41ce580 211 // Send our "last state" informations to opponent
411d23cd 212 const L = this.game.moves.length;
a0c41e7e 213 const myIdx = ["w","b"].indexOf(this.game.mycolor);
411d23cd
BA
214 this.st.conn.send(JSON.stringify({
215 code: "lastate",
a0c41e7e 216 target: data.from,
f41ce580
BA
217 state:
218 {
a0c41e7e
BA
219 // NOTE: lastMove (when defined) includes addTime
220 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
221 // Since we played a move (or abort or resign),
222 // only drawOffer=="sent" is possible
77c50966 223 drawSent: this.drawOffer == "sent",
f41ce580
BA
224 score: this.game.score,
225 movesCount: L,
a0c41e7e 226 initime: this.game.initime[1-myIdx], //relevant only if I played
f41ce580 227 }
411d23cd
BA
228 }));
229 }
a6088c90 230 break;
c6788ecf 231 case "askgame":
5fd5fb22
BA
232 // Send current (live) game if I play in (not an observer),
233 // and not asked by opponent (!)
234 if (this.game.type == "live"
235 && this.game.players.some(p => p.sid == this.st.user.sid)
236 && this.game.players.every(p => p.sid != data.from))
c6788ecf 237 {
5fd5fb22
BA
238 const myGame =
239 {
240 // Minimal game informations:
241 id: this.game.id,
242 players: this.game.players,
243 vid: this.game.vid,
244 timeControl: this.game.timeControl,
26f3a887 245 score: this.game.score,
5fd5fb22
BA
246 };
247 this.st.conn.send(JSON.stringify({code:"game",
248 game:myGame, target:data.from}));
249 }
c6788ecf 250 break;
f41ce580 251 case "newmove":
77c50966 252 if (!!data.move.cancelDrawOffer) //opponent refuses draw
633959bf 253 {
77c50966 254 this.drawOffer = "";
c4f6d5a1
BA
255 // NOTE for corr games: drawOffer reset by player in turn
256 if (this.game.type == "live" && !!this.game.mycolor)
633959bf
BA
257 GameStorage.update(this.gameRef.id, {drawOffer: ""});
258 }
41c80bb6 259 this.$set(this.game, "moveToPlay", data.move);
f41ce580 260 break;
ac8f441c
BA
261 case "newchat":
262 this.newChat = data.chat;
263 if (!document.getElementById("modalChat").checked)
264 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
265 break;
a6088c90 266 case "lastate": //got opponent infos about last move
a0c41e7e
BA
267 this.lastate = data.state;
268 if (this.game.rendered) //game is rendered (Board component)
760adbce
BA
269 this.processLastate();
270 //else: will be processed when game is ready
a6088c90 271 break;
93d1d7a7 272 case "resign":
77c50966 273 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
93d1d7a7 274 break;
93d1d7a7 275 case "abort":
77c50966 276 this.gameOver("?", "Abort");
93d1d7a7 277 break;
2cc10cdb 278 case "draw":
77c50966 279 this.gameOver("1/2", data.message);
2cc10cdb
BA
280 break;
281 case "drawoffer":
41c80bb6
BA
282 // NOTE: observers don't know who offered draw
283 this.drawOffer = "received";
6d9f4315 284 break;
7e1a1fe9 285 case "askfullgame":
41c80bb6
BA
286 this.st.conn.send(JSON.stringify({code:"fullgame",
287 game:this.game, target:data.from}));
7e1a1fe9 288 break;
5f131484 289 case "fullgame":
760adbce
BA
290 // Callback "roomInit" to poll clients only after game is loaded
291 this.loadGame(data.game, this.roomInit);
5f131484 292 break;
5f131484 293 case "connect":
a0c41e7e
BA
294 this.$set(this.people, data.from, {name:"", id:0});
295 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
5f131484 296 break;
5f131484 297 case "disconnect":
dcd68c41 298 this.$delete(this.people, data.from);
a6088c90
BA
299 break;
300 }
cdb34c93 301 },
760adbce
BA
302 // lastate was received, but maybe game wasn't ready yet:
303 processLastate: function() {
304 const data = this.lastate;
305 this.lastate = undefined; //security...
306 const L = this.game.moves.length;
307 if (data.movesCount > L)
308 {
309 // Just got last move from him
a0c41e7e
BA
310 this.$set(this.game, "moveToPlay", Object.assign({}, data.lastMove, {initime: data.initime}));
311 }
633959bf
BA
312 if (data.drawSent)
313 this.drawOffer = "received";
a0c41e7e
BA
314 if (data.score != "*")
315 {
316 this.drawOffer = "";
317 if (this.game.score == "*")
318 this.gameOver(data.score);
760adbce
BA
319 }
320 },
dcd68c41 321 clickDraw: function() {
77c50966
BA
322 if (!this.game.mycolor)
323 return; //I'm just spectator
a1c48034 324 if (["received","threerep"].includes(this.drawOffer))
6fba6e0c 325 {
602d6bef 326 if (!confirm(this.st.tr["Accept draw?"]))
6fba6e0c 327 return;
a1c48034
BA
328 const message = (this.drawOffer == "received"
329 ? "Mutual agreement"
330 : "Three repetitions");
dcd68c41
BA
331 Object.keys(this.people).forEach(sid => {
332 if (sid != this.st.user.sid)
333 {
334 this.st.conn.send(JSON.stringify({code:"draw",
335 message:message, target:sid}));
336 }
337 });
77c50966 338 this.gameOver("1/2", message);
2cc10cdb 339 }
41c80bb6 340 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
6fba6e0c 341 {
dfeb96ea
BA
342 if (this.game.mycolor != this.vr.turn)
343 return alert(this.st.tr["Draw offer only in your turn"]);
602d6bef 344 if (!confirm(this.st.tr["Offer draw?"]))
6fba6e0c 345 return;
760adbce 346 this.drawOffer = "sent";
dcd68c41
BA
347 Object.keys(this.people).forEach(sid => {
348 if (sid != this.st.user.sid)
349 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
760adbce 350 });
dfeb96ea 351 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
a6088c90
BA
352 }
353 },
7f3484bd 354 abortGame: function() {
77c50966 355 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
7f3484bd 356 return;
77c50966 357 this.gameOver("?", "Abort");
dcd68c41
BA
358 Object.keys(this.people).forEach(sid => {
359 if (sid != this.st.user.sid)
5f131484
BA
360 {
361 this.st.conn.send(JSON.stringify({
362 code: "abort",
dcd68c41 363 target: sid,
5f131484
BA
364 }));
365 }
7f3484bd 366 });
a6088c90
BA
367 },
368 resign: function(e) {
77c50966 369 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
a6088c90 370 return;
dcd68c41
BA
371 Object.keys(this.people).forEach(sid => {
372 if (sid != this.st.user.sid)
760adbce
BA
373 {
374 this.st.conn.send(JSON.stringify({code:"resign",
dcd68c41 375 side:this.game.mycolor, target:sid}));
760adbce
BA
376 }
377 });
77c50966 378 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 379 },
967a2686
BA
380 // 3 cases for loading a game:
381 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
382 // - from server (one correspondance game I play[ed] or not)
383 // - from remote peer (one live game I don't play, finished or not)
760adbce 384 loadGame: function(game, callback) {
967a2686 385 const afterRetrieval = async (game) => {
f41ce580
BA
386 const vModule = await import("@/variants/" + game.vname + ".js");
387 window.V = vModule.VariantRules;
388 this.vr = new V(game.fen);
c0b27606 389 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
92a523d1 390 const tc = extractTime(game.timeControl);
c0b27606
BA
391 if (gtype == "corr")
392 {
f41ce580
BA
393 if (game.players[0].color == "b")
394 {
395 // Adopt the same convention for live and corr games: [0] = white
396 [ game.players[0], game.players[1] ] =
397 [ game.players[1], game.players[0] ];
398 }
c0b27606 399 // corr game: needs to compute the clocks + initime
7f3484bd 400 // NOTE: clocks in seconds, initime in milliseconds
92a523d1 401 game.clocks = [tc.mainTime, tc.mainTime];
92b82def 402 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
b7cbbda1 403 if (game.score == "*") //otherwise no need to bother with time
92a523d1 404 {
b7cbbda1
BA
405 game.initime = [0, 0];
406 const L = game.moves.length;
407 if (L >= 3)
5f131484 408 {
b7cbbda1
BA
409 let addTime = [0, 0];
410 for (let i=2; i<L; i++)
411 {
412 addTime[i%2] += tc.increment -
413 (game.moves[i].played - game.moves[i-1].played) / 1000;
414 }
415 for (let i=0; i<=1; i++)
416 game.clocks[i] += addTime[i];
5f131484 417 }
b7cbbda1
BA
418 if (L >= 1)
419 game.initime[L%2] = game.moves[L-1].played;
92a523d1 420 }
92b82def 421 // Now that we used idx and played, re-format moves as for live games
6d68309a 422 game.moves = game.moves.map( (m) => {
92b82def 423 const s = m.squares;
6d68309a 424 return {
92b82def
BA
425 appear: s.appear,
426 vanish: s.vanish,
427 start: s.start,
428 end: s.end,
92b82def
BA
429 };
430 });
3837d4f7
BA
431 // Also sort chat messages (if any)
432 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
c0b27606 433 }
f41ce580
BA
434 const myIdx = game.players.findIndex(p => {
435 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
436 });
92a523d1 437 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
66d03f23
BA
438 {
439 game.clocks = [tc.mainTime, tc.mainTime];
b7cbbda1 440 if (game.score == "*")
22efa391 441 {
b7cbbda1
BA
442 game.initime[0] = Date.now();
443 if (myIdx >= 0)
22efa391 444 {
b7cbbda1
BA
445 // I play in this live game; corr games don't have clocks+initime
446 GameStorage.update(game.id,
447 {
448 clocks: game.clocks,
449 initime: game.initime,
450 });
451 }
22efa391 452 }
66d03f23 453 }
77c50966
BA
454 if (!!game.drawOffer)
455 {
456 if (game.drawOffer == "t") //three repetitions
457 this.drawOffer = "threerep";
458 else
459 {
460 if (myIdx < 0)
461 this.drawOffer = "received"; //by any of the players
462 else
463 {
464 // I play in this game:
465 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
466 this.drawOffer = "sent";
467 else //all other cases
468 this.drawOffer = "received";
469 }
470 }
471 }
472 if (!!game.scoreMsg)
473 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
4b0384fa
BA
474 this.game = Object.assign({},
475 game,
cf742aaf 476 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 477 {
c0b27606 478 type: gtype,
66d03f23 479 increment: tc.increment,
6fba6e0c 480 mycolor: [undefined,"w","b"][myIdx+1],
5f131484
BA
481 // opponent sid not strictly required (or available), but easier
482 // at least oppsid or oppid is available anyway:
483 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
484 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
6fba6e0c 485 }
4b0384fa 486 );
a0c41e7e
BA
487 this.$nextTick(() => {
488 this.game.rendered = true;
489 // Did lastate arrive before game was rendered?
490 if (!!this.lastate)
491 this.processLastate();
492 });
77c50966
BA
493 this.repeat = {}; //reset: scan past moves' FEN:
494 let repIdx = 0;
495 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
496 let vr_tmp = new V(game.fenStart);
497 game.moves.forEach(m => {
498 vr_tmp.play(m);
499 const fenObj = V.ParseFen( vr_tmp.getFen() );
500 repIdx = fenObj.position + "_" + fenObj.turn;
501 if (!!fenObj.flags)
502 repIdx += "_" + fenObj.flags;
503 this.repeat[repIdx] = (!!this.repeat[repIdx]
504 ? this.repeat[repIdx]+1
505 : 1);
506 });
507 if (this.repeat[repIdx] >= 3)
508 this.drawOffer = "threerep";
760adbce 509 callback();
967a2686
BA
510 };
511 if (!!game)
dc284d90 512 return afterRetrieval(game);
967a2686
BA
513 if (!!this.gameRef.rid)
514 {
760adbce 515 // Remote live game: forgetting about callback func... (TODO: design)
5f131484
BA
516 this.st.conn.send(JSON.stringify(
517 {code:"askfullgame", target:this.gameRef.rid}));
967a2686
BA
518 }
519 else
520 {
f41ce580 521 // Local or corr game
11667c79 522 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 523 }
a6088c90 524 },
9d54ab89 525 // Post-process a move (which was just played)
ce87ac6a 526 processMove: function(move) {
a1c48034 527 // Update storage (corr or live) if I play in the game
6fba6e0c 528 const colorIdx = ["w","b"].indexOf(move.color);
a0c41e7e 529 const nextIdx = ["w","b"].indexOf(this.vr.turn);
9d54ab89 530 // https://stackoverflow.com/a/38750895
a1c48034
BA
531 if (!!this.game.mycolor)
532 {
533 const allowed_fields = ["appear", "vanish", "start", "end"];
534 // NOTE: 'var' to see this variable outside this block
535 var filtered_move = Object.keys(move)
536 .filter(key => allowed_fields.includes(key))
537 .reduce((obj, key) => {
538 obj[key] = move[key];
539 return obj;
540 }, {});
541 }
dc284d90 542 // Send move ("newmove" event) to people in the room (if our turn)
dce792f6 543 let addTime = 0;
9d54ab89 544 if (move.color == this.game.mycolor)
b4fb1612 545 {
77c50966
BA
546 if (this.drawOffer == "received") //I refuse draw
547 this.drawOffer = "";
dce792f6
BA
548 if (this.game.moves.length >= 2) //after first move
549 {
550 const elapsed = Date.now() - this.game.initime[colorIdx];
551 // elapsed time is measured in milliseconds
552 addTime = this.game.increment - elapsed/1000;
553 }
633959bf
BA
554 const sendMove = Object.assign({},
555 filtered_move,
556 {
557 addTime: addTime,
558 cancelDrawOffer: this.drawOffer=="",
559 });
dcd68c41
BA
560 Object.keys(this.people).forEach(sid => {
561 if (sid != this.st.user.sid)
dc284d90
BA
562 {
563 this.st.conn.send(JSON.stringify({
564 code: "newmove",
dcd68c41 565 target: sid,
dc284d90
BA
566 move: sendMove,
567 }));
568 }
569 });
a0c41e7e
BA
570 // (Add)Time indication: useful in case of lastate infos requested
571 move.addTime = addTime;
b4fb1612 572 }
5b87454c
BA
573 else
574 addTime = move.addTime; //supposed transmitted
77c50966
BA
575 // Update current game object:
576 this.game.moves.push(move);
577 this.game.fen = move.fen;
578 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
a0c41e7e
BA
579 // move.initime is set only when I receive a "lastate" move from opponent
580 this.game.initime[nextIdx] = move.initime || Date.now();
77c50966
BA
581 // If repetition detected, consider that a draw offer was received:
582 const fenObj = V.ParseFen(move.fen);
583 let repIdx = fenObj.position + "_" + fenObj.turn;
584 if (!!fenObj.flags)
585 repIdx += "_" + fenObj.flags;
586 this.repeat[repIdx] = (!!this.repeat[repIdx]
587 ? this.repeat[repIdx]+1
588 : 1);
589 if (this.repeat[repIdx] >= 3)
590 this.drawOffer = "threerep";
591 else if (this.drawOffer == "threerep")
592 this.drawOffer = "";
6d68309a
BA
593 // Since corr games are stored at only one location, update should be
594 // done only by one player for each move:
a1c48034
BA
595 if (!!this.game.mycolor &&
596 (this.game.type == "live" || move.color == this.game.mycolor))
967a2686 597 {
77c50966
BA
598 let drawCode = "";
599 switch (this.drawOffer)
600 {
601 case "threerep":
602 drawCode = "t";
603 break;
604 case "sent":
605 drawCode = this.game.mycolor;
606 break;
607 case "received":
608 drawCode = this.vr.turn;
609 break;
610 }
e69f159d 611 if (this.game.type == "corr")
f41ce580 612 {
e69f159d 613 GameStorage.update(this.gameRef.id,
6d68309a 614 {
e69f159d
BA
615 fen: move.fen,
616 move:
617 {
618 squares: filtered_move,
a0c41e7e 619 played: Date.now(),
77c50966 620 idx: this.game.moves.length - 1,
e69f159d 621 },
633959bf 622 drawOffer: drawCode || "n", //"n" for "None" to force reset (otherwise it's ignored)
e69f159d
BA
623 });
624 }
625 else //live
626 {
627 GameStorage.update(this.gameRef.id,
628 {
629 fen: move.fen,
630 move: filtered_move,
77c50966
BA
631 clocks: this.game.clocks,
632 initime: this.game.initime,
633 drawOffer: drawCode,
e69f159d
BA
634 });
635 }
6d68309a 636 }
b4fb1612 637 },
bfe9a135
BA
638 resetChatColor: function() {
639 // TODO: this is called twice, once on opening an once on closing
640 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
a1c48034 641 },
ac8f441c
BA
642 processChat: function(chat) {
643 this.st.conn.send(JSON.stringify({code:"newchat", chat:chat}));
0e16cb26
BA
644 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
645 if (this.game.type == "corr" && this.st.user.id > 0)
63ca2b89
BA
646 GameStorage.update(this.gameRef.id, {chat: chat});
647 },
430a2038 648 gameOver: function(score, scoreMsg) {
430a2038 649 this.game.score = score;
77c50966
BA
650 this.game.scoreMsg = this.st.tr[(!!scoreMsg
651 ? scoreMsg
652 : getScoreMessage(score))];
ab6f48ea
BA
653 const myIdx = this.game.players.findIndex(p => {
654 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
655 });
656 if (myIdx >= 0) //OK, I play in this game
dcd68c41
BA
657 {
658 GameStorage.update(this.gameRef.id,
659 {score: score, scoreMsg: scoreMsg});
660 }
ce87ac6a 661 },
a6088c90
BA
662 },
663};
664</script>
7e1a1fe9 665
41c80bb6 666<style lang="sass" scoped>
72ccbd67 667.connected
050ae3b5 668 background-color: lightgreen
72ccbd67 669
ed06d9e9
BA
670#participants
671 margin-left: 5px
672
673.anonymous
674 color: grey
675 font-style: italic
676
430a2038
BA
677@media screen and (min-width: 768px)
678 #actions
679 width: 300px
680@media screen and (max-width: 767px)
681 .game
682 width: 100%
72ccbd67 683
430a2038 684#actions
cf94b843 685 display: inline-block
430a2038 686 margin-top: 10px
430a2038
BA
687 button
688 display: inline-block
430a2038 689 margin: 0
a1c48034 690
050ae3b5
BA
691@media screen and (max-width: 767px)
692 #aboveBoard
693 text-align: center
885d93a7
BA
694@media screen and (min-width: 768px)
695 #aboveBoard
696 margin-left: 30%
050ae3b5 697
77c50966 698.variant-info
8c5f5390 699 font-weight: bold
77c50966 700 padding-right: 10px
77c50966 701
050ae3b5
BA
702.name
703 font-size: 1.5rem
704 padding: 1px
705
706.time
707 font-size: 2rem
708 display: inline-block
709 margin-left: 10px
710
711.split-names
712 display: inline-block
713 margin: 0 15px
714
430a2038 715#chat
a1c48034
BA
716 padding-top: 20px
717 max-width: 600px
430a2038 718 border: none;
cf94b843
BA
719
720#chatBtn
721 margin: 0 10px 0 0
dcd68c41
BA
722
723.draw-sent, .draw-sent:hover
724 background-color: lightyellow
725
726.draw-received, .draw-received:hover
727 background-color: lightgreen
728
729.draw-threerep, .draw-threerep:hover
730 background-color: #e4d1fc
7e1a1fe9 731</style>