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