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