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