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