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