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