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