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