Fix: send fullgame without irrelevant fields
[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)"
efdfb4c7 17 v-if="p.name"
910d631b 18 )
ed06d9e9 19 | {{ p.name }}
efdfb4c7 20 span.anonymous(v-if="Object.values(people).some(p => !p.name && p.id === 0)")
ed06d9e9 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" }}
57eb158f
BA
54 span.time(
55 v-if="game.score=='*'"
56 :class="{yourturn: !!vr && vr.turn == 'w'}"
57 )
58 span.time-left {{ virtualClocks[0][0] }}
59 span.time-separator(v-if="!!virtualClocks[0][1]") :
60 span.time-right(v-if="!!virtualClocks[0][1]") {{ virtualClocks[0][1] }}
050ae3b5 61 span.split-names -
5bcc9b31
BA
62 span.name(:class="{connected: isConnected(1)}")
63 | {{ game.players[1].name || "@nonymous" }}
57eb158f
BA
64 span.time(
65 v-if="game.score=='*'"
66 :class="{yourturn: !!vr && vr.turn == 'b'}"
67 )
68 span.time-left {{ virtualClocks[1][0] }}
69 span.time-separator(v-if="!!virtualClocks[1][1]") :
70 span.time-right(v-if="!!virtualClocks[1][1]") {{ virtualClocks[1][1] }}
910d631b 71 BaseGame(
8477e53d 72 ref="basegame"
910d631b 73 :game="game"
910d631b
BA
74 @newmove="processMove"
75 @gameover="gameOver"
76 )
a6088c90
BA
77</template>
78
79<script>
46284a2f 80import BaseGame from "@/components/BaseGame.vue";
f21cd6d9 81import Chat from "@/components/Chat.vue";
a6088c90 82import { store } from "@/store";
967a2686 83import { GameStorage } from "@/utils/gameStorage";
5b87454c 84import { ppt } from "@/utils/datetime";
23ecf008 85import { ajax } from "@/utils/ajax";
66d03f23 86import { extractTime } from "@/utils/timeControl";
51d87b52 87import { getRandString } from "@/utils/alea";
dcd68c41 88import { processModalClick } from "@/utils/modalClick";
e71161fb
BA
89import { getFullNotation } from "@/utils/notation";
90import { playMove, getFilteredMove } from "@/utils/playUndo";
77c50966 91import { getScoreMessage } from "@/utils/scoring";
1611a25f 92import { ArrayFun } from "@/utils/array";
8418f0d7 93import params from "@/parameters";
a6088c90 94export default {
6808d7a1 95 name: "my-game",
a6088c90
BA
96 components: {
97 BaseGame,
6808d7a1 98 Chat
a6088c90 99 },
f7121527 100 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
101 data: function() {
102 return {
103 st: store.state,
6808d7a1 104 gameRef: {
1611a25f 105 // rid = remote (socket) ID
4b0384fa
BA
106 id: "",
107 rid: ""
108 },
6808d7a1 109 game: {
1611a25f 110 // Passed to BaseGame
6808d7a1 111 players: [{ name: "" }, { name: "" }],
9a3049f3 112 chats: [],
6808d7a1 113 rendered: false
a0c41e7e 114 },
57eb158f 115 virtualClocks: [[0,0], [0,0]], //initialized with true game.clocks
6dd02928 116 vr: null, //"variant rules" object initialized from FEN
dcd68c41
BA
117 drawOffer: "",
118 people: {}, //players + observers
1611a25f 119 onMygames: [], //opponents (or me) on "MyGames" page
760adbce 120 lastate: undefined, //used if opponent send lastate before game is ready
72ccbd67 121 repeat: {}, //detect position repetition
ac8f441c 122 newChat: "",
8418f0d7 123 conn: null,
f9c36b2d
BA
124 roomInitialized: false,
125 // If newmove has wrong index: ask fullgame again:
57eb158f 126 askGameTime: 0,
dcff8e82 127 gameIsLoading: false,
f9c36b2d
BA
128 // If asklastate got no reply, ask again:
129 gotLastate: false,
e5c1d0fb 130 gotMoveIdx: -1, //last move index received
f9c36b2d
BA
131 // If newmove got no pingback, send again:
132 opponentGotMove: false,
51d87b52
BA
133 connexionString: "",
134 // Related to (killing of) self multi-connects:
135 newConnect: {},
6808d7a1 136 killed: {}
a6088c90
BA
137 };
138 },
139 watch: {
6808d7a1 140 $route: function(to) {
5f131484
BA
141 this.gameRef.id = to.params["id"];
142 this.gameRef.rid = to.query["rid"];
143 this.loadGame();
6808d7a1 144 }
92a523d1 145 },
71468011 146 // NOTE: some redundant code with Hall.vue (mostly related to people array)
a6088c90 147 created: function() {
5f131484
BA
148 // Always add myself to players' list
149 const my = this.st.user;
6808d7a1 150 this.$set(this.people, my.sid, { id: my.id, name: my.name });
dc284d90
BA
151 this.gameRef.id = this.$route.params["id"];
152 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
8418f0d7 153 // Initialize connection
6808d7a1
BA
154 this.connexionString =
155 params.socketUrl +
156 "/?sid=" +
157 this.st.user.sid +
158 "&tmpId=" +
159 getRandString() +
160 "&page=" +
161 encodeURIComponent(this.$route.path);
51d87b52 162 this.conn = new WebSocket(this.connexionString);
8418f0d7 163 this.conn.onmessage = this.socketMessageListener;
51d87b52 164 this.conn.onclose = this.socketCloseListener;
760adbce 165 // Socket init required before loading remote game:
6808d7a1
BA
166 const socketInit = callback => {
167 if (!!this.conn && this.conn.readyState == 1)
8477e53d 168 // 1 == OPEN state
760adbce 169 callback();
1611a25f 170 else
8477e53d 171 // Socket not ready yet (initial loading)
7f36b53a
BA
172 // NOTE: it's important to call callback without arguments,
173 // otherwise first arg is Websocket object and loadGame fails.
1611a25f 174 this.conn.onopen = () => callback();
760adbce 175 };
6808d7a1 176 if (!this.gameRef.rid)
8477e53d 177 // Game stored locally or on server
760adbce 178 this.loadGame(null, () => socketInit(this.roomInit));
1611a25f 179 else
8477e53d 180 // Game stored remotely: need socket to retrieve it
760adbce
BA
181 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
182 // --> It will be given when receiving "fullgame" socket event.
760adbce 183 socketInit(this.loadGame);
cdb34c93 184 },
dcd68c41 185 mounted: function() {
6808d7a1
BA
186 document
187 .getElementById("chatWrap")
188 .addEventListener("click", processModalClick);
dcd68c41 189 },
8418f0d7 190 beforeDestroy: function() {
71468011 191 this.send("disconnect");
8418f0d7 192 },
cdb34c93 193 methods: {
760adbce 194 roomInit: function() {
f9c36b2d
BA
195 if (!this.roomInitialized) {
196 // Notify the room only now that I connected, because
197 // messages might be lost otherwise (if game loading is slow)
198 this.send("connect");
199 this.send("pollclients");
200 // We may ask fullgame several times if some moves are lost,
201 // but room should be init only once:
202 this.roomInitialized = true;
203 }
71468011
BA
204 },
205 send: function(code, obj) {
f9c36b2d 206 if (!!this.conn)
6808d7a1 207 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
5f131484 208 },
050ae3b5 209 isConnected: function(index) {
29ced362
BA
210 const player = this.game.players[index];
211 // Is it me ?
212 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
050ae3b5 213 return true;
29ced362 214 // Try to find a match in people:
6808d7a1 215 return (
1611a25f
BA
216 (
217 player.sid &&
218 Object.keys(this.people).some(sid => sid == player.sid)
219 )
220 ||
221 (
222 player.uid &&
223 Object.values(this.people).some(p => p.id == player.uid)
224 )
6808d7a1 225 );
050ae3b5 226 },
db1f1f9a
BA
227 resetChatColor: function() {
228 // TODO: this is called twice, once on opening an once on closing
229 document.getElementById("chatBtn").classList.remove("somethingnew");
230 },
231 processChat: function(chat) {
232 this.send("newchat", { data: chat });
233 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
234 if (this.game.type == "corr" && this.st.user.id > 0)
235 GameStorage.update(this.gameRef.id, { chat: chat });
236 },
237 clearChat: function() {
238 // Nothing more to do if game is live (chats not recorded)
23ecf008 239 if (this.game.type == "corr") {
f9c36b2d 240 if (!!this.game.mycolor)
23ecf008 241 ajax("/chats", "DELETE", {gid: this.game.id});
dcff8e82 242 this.$set(this.game, "chats", []);
db1f1f9a
BA
243 }
244 },
1611a25f
BA
245 // Notify turn after a new move (to opponent and me on MyGames page)
246 notifyTurn: function(sid) {
247 const player = this.people[sid];
248 const colorIdx = this.game.players.findIndex(
8f4e861c 249 p => p.sid == sid || p.uid == player.id);
1611a25f 250 const color = ["w","b"][colorIdx];
dcff8e82 251 const movesCount = this.game.moves.length;
1611a25f 252 const yourTurn =
dcff8e82
BA
253 (color == "w" && movesCount % 2 == 0) ||
254 (color == "b" && movesCount % 2 == 1);
1611a25f
BA
255 this.send("turnchange", { target: sid, yourTurn: yourTurn });
256 },
d6f08e56
BA
257 askGameAgain: function() {
258 this.gameIsLoading = true;
57eb158f
BA
259 const doAskGame = () => {
260 if (!this.gameRef.rid)
261 // This is my game: just reload.
262 this.loadGame();
263 else {
264 // Just ask fullgame again (once!), this is much simpler.
265 // If this fails, the user could just reload page :/
266 let self = this;
267 (function askIfPeerConnected() {
268 if (!!self.people[self.gameRef.rid])
269 self.send("askfullgame", { target: self.gameRef.rid });
270 else setTimeout(askIfPeerConnected, 1000);
271 })();
272 }
273 };
274 // Delay of at least 2s between two game requests
275 const now = Date.now();
276 const delay = Math.max(2000 - (now - this.askGameTime), 0);
277 this.askGameTime = now;
278 setTimeout(doAskGame, delay);
d6f08e56 279 },
cdb34c93 280 socketMessageListener: function(msg) {
6808d7a1 281 if (!this.conn) return;
a6088c90 282 const data = JSON.parse(msg.data);
6808d7a1 283 switch (data.code) {
5f131484 284 case "pollclients":
5f131484 285 data.sockIds.forEach(sid => {
dcff8e82 286 if (sid != this.st.user.sid)
6808d7a1 287 this.send("askidentity", { target: sid });
5f131484
BA
288 });
289 break;
71468011 290 case "connect":
efdfb4c7 291 if (!this.people[data.from]) {
51d87b52 292 this.newConnect[data.from] = true; //for self multi-connects tests
6808d7a1 293 this.send("askidentity", { target: data.from });
51d87b52 294 }
71468011
BA
295 break;
296 case "disconnect":
297 this.$delete(this.people, data.from);
298 break;
efdfb4c7 299 case "mconnect": {
1611a25f
BA
300 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
301 // Either me (another tab) or opponent
302 const sid = data.from;
303 if (!this.onMygames.some(s => s == sid))
304 {
305 this.onMygames.push(sid);
306 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
307 }
308 break;
309 if (!this.people[sid])
310 this.send("askidentity", { target: sid });
311 }
312 case "mdisconnect":
313 ArrayFun.remove(this.onMygames, sid => sid == data.from);
314 break;
51d87b52
BA
315 case "killed":
316 // I logged in elsewhere:
51d87b52 317 this.conn = null;
09d37571 318 alert(this.st.tr["New connexion detected: tab now offline"]);
51d87b52 319 break;
6808d7a1 320 case "askidentity": {
efdfb4c7 321 // Request for identification
51d87b52
BA
322 const me = {
323 // Decompose to avoid revealing email
324 name: this.st.user.name,
325 sid: this.st.user.sid,
6808d7a1 326 id: this.st.user.id
51d87b52 327 };
6808d7a1 328 this.send("identity", { data: me, target: data.from });
5f131484 329 break;
51d87b52 330 }
6808d7a1 331 case "identity": {
71468011 332 const user = data.data;
efdfb4c7 333 this.$set(this.people, user.sid, { name: user.name, id: user.id });
f9c36b2d
BA
334 // If I multi-connect, kill current connexion if no mark (I'm older)
335 if (this.newConnect[user.sid]) {
6808d7a1 336 if (
6808d7a1
BA
337 user.id > 0 &&
338 user.id == this.st.user.id &&
f9c36b2d
BA
339 user.sid != this.st.user.sid &&
340 !this.killed[this.st.user.sid]
6808d7a1 341 ) {
6808d7a1 342 this.send("killme", { sid: this.st.user.sid });
51d87b52 343 this.killed[this.st.user.sid] = true;
51d87b52 344 }
f9c36b2d 345 delete this.newConnect[user.sid];
a0c41e7e 346 }
dcff8e82
BA
347 if (!this.killed[this.st.user.sid]) {
348 // Ask potentially missed last state, if opponent and I play
349 if (
350 !!this.game.mycolor &&
351 this.game.type == "live" &&
352 this.game.score == "*" &&
353 this.game.players.some(p => p.sid == user.sid)
354 ) {
355 let self = this;
356 (function askLastate() {
357 self.send("asklastate", { target: user.sid });
358 setTimeout(
359 () => {
360 // Ask until we got a reply (or opponent disconnect):
361 if (!self.gotLastate && !!self.people[user.sid])
362 askLastate();
363 },
57eb158f 364 1000
dcff8e82
BA
365 );
366 })();
367 }
368 }
a0c41e7e 369 break;
71468011
BA
370 }
371 case "askgame":
372 // Send current (live) game if not asked by any of the players
6808d7a1
BA
373 if (
374 this.game.type == "live" &&
375 this.game.players.every(p => p.sid != data.from[0])
376 ) {
71468011
BA
377 const myGame = {
378 id: this.game.id,
379 fen: this.game.fen,
380 players: this.game.players,
381 vid: this.game.vid,
382 cadence: this.game.cadence,
383 score: this.game.score,
6808d7a1 384 rid: this.st.user.sid //useful in Hall if I'm an observer
71468011 385 };
6808d7a1 386 this.send("game", { data: myGame, target: data.from });
71468011
BA
387 }
388 break;
389 case "askfullgame":
e8da204a
BA
390 const gameToSend = Object.keys(this.game)
391 .filter(k =>
392 [
393 "id","fen","players","vid","cadence","fenStart","vname",
394 "moves","clocks","initime","score","drawOffer"
395 ].includes(k))
396 .reduce(
397 (obj, k) => {
398 obj[k] = this.game[k];
399 return obj;
400 },
401 {}
402 );
403 this.send("fullgame", { data: gameToSend, target: data.from });
71468011
BA
404 break;
405 case "fullgame":
406 // Callback "roomInit" to poll clients only after game is loaded
dcff8e82 407 this.loadGame(data.data, this.roomInit);
71468011 408 break;
a0c41e7e 409 case "asklastate":
dcff8e82 410 // Sending informative last state if I played a move or score != "*"
6808d7a1
BA
411 if (
412 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
413 this.game.score != "*" ||
414 this.drawOffer == "sent"
415 ) {
f41ce580 416 // Send our "last state" informations to opponent
411d23cd 417 const L = this.game.moves.length;
6808d7a1 418 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
71468011 419 const myLastate = {
6808d7a1 420 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
dcff8e82 421 addTime: L > 0 ? this.game.addTimes[L - 1] : undefined,
71468011
BA
422 // Since we played a move (or abort or resign),
423 // only drawOffer=="sent" is possible
424 drawSent: this.drawOffer == "sent",
26f3a887 425 score: this.game.score,
71468011 426 movesCount: L,
6808d7a1 427 initime: this.game.initime[1 - myIdx] //relevant only if I played
5fd5fb22 428 };
6808d7a1 429 this.send("lastate", { data: myLastate, target: data.from });
dcff8e82
BA
430 } else {
431 this.send("lastate", { data: {nothing: true}, target: data.from });
5fd5fb22 432 }
c6788ecf 433 break;
dcff8e82
BA
434 case "lastate": {
435 // Got opponent infos about last move
436 this.gotLastate = true;
437 if (!data.data.nothing) {
438 this.lastate = data.data;
439 if (this.game.rendered)
440 // Game is rendered (Board component)
441 this.processLastate();
442 // Else: will be processed when game is ready
443 }
71468011 444 break;
dcff8e82 445 }
6808d7a1 446 case "newmove": {
dcff8e82
BA
447 const movePlus = data.data;
448 const movesCount = this.game.moves.length;
449 if (movePlus.index > movesCount) {
450 // This can only happen if I'm an observer and missed a move.
57eb158f
BA
451 if (this.gotMoveIdx < movePlus.index)
452 this.gotMoveIdx = movePlus.index;
d6f08e56
BA
453 if (!this.gameIsLoading) this.askGameAgain();
454 }
455 else {
f9c36b2d 456 if (
dcff8e82
BA
457 movePlus.index < movesCount ||
458 this.gotMoveIdx >= movePlus.index
f9c36b2d
BA
459 ) {
460 // Opponent re-send but we already have the move:
461 // (maybe he didn't receive our pingback...)
dcff8e82 462 this.send("gotmove", {data: movePlus.index, target: data.from});
f9c36b2d 463 } else {
dcff8e82
BA
464 this.gotMoveIdx = movePlus.index;
465 const receiveMyMove = (movePlus.color == this.game.mycolor);
f9c36b2d
BA
466 if (!receiveMyMove && !!this.game.mycolor)
467 // Notify opponent that I got the move:
dcff8e82
BA
468 this.send("gotmove", {data: movePlus.index, target: data.from});
469 if (movePlus.cancelDrawOffer) {
f9c36b2d
BA
470 // Opponent refuses draw
471 this.drawOffer = "";
472 // NOTE for corr games: drawOffer reset by player in turn
473 if (
474 this.game.type == "live" &&
475 !!this.game.mycolor &&
476 !receiveMyMove
477 ) {
478 GameStorage.update(this.gameRef.id, { drawOffer: "" });
479 }
480 }
57eb158f
BA
481 this.$refs["basegame"].play(movePlus.move, "received", null, true);
482 this.processMove(
dcff8e82 483 movePlus.move,
f9c36b2d 484 {
dcff8e82 485 addTime: movePlus.addTime,
f9c36b2d
BA
486 receiveMyMove: receiveMyMove
487 }
488 );
489 }
633959bf 490 }
a6088c90 491 break;
71468011 492 }
f9c36b2d
BA
493 case "gotmove": {
494 this.opponentGotMove = true;
495 break;
496 }
93d1d7a7 497 case "resign":
8477e53d
BA
498 const score = data.side == "b" ? "1-0" : "0-1";
499 const side = data.side == "w" ? "White" : "Black";
500 this.gameOver(score, side + " surrender");
93d1d7a7 501 break;
93d1d7a7 502 case "abort":
8477e53d 503 this.gameOver("?", "Stop");
93d1d7a7 504 break;
2cc10cdb 505 case "draw":
71468011 506 this.gameOver("1/2", data.data);
2cc10cdb
BA
507 break;
508 case "drawoffer":
41c80bb6
BA
509 // NOTE: observers don't know who offered draw
510 this.drawOffer = "received";
6d9f4315 511 break;
71468011 512 case "newchat":
bd76b456 513 this.newChat = data.data;
71468011 514 if (!document.getElementById("modalChat").checked)
2f258c37 515 document.getElementById("chatBtn").classList.add("somethingnew");
a6088c90
BA
516 break;
517 }
cdb34c93 518 },
51d87b52
BA
519 socketCloseListener: function() {
520 this.conn = new WebSocket(this.connexionString);
6808d7a1
BA
521 this.conn.addEventListener("message", this.socketMessageListener);
522 this.conn.addEventListener("close", this.socketCloseListener);
51d87b52 523 },
760adbce
BA
524 // lastate was received, but maybe game wasn't ready yet:
525 processLastate: function() {
526 const data = this.lastate;
527 this.lastate = undefined; //security...
528 const L = this.game.moves.length;
6808d7a1 529 if (data.movesCount > L) {
760adbce 530 // Just got last move from him
8477e53d 531 this.$refs["basegame"].play(
dcff8e82 532 data.lastMove,
e71161fb
BA
533 "received",
534 null,
dcff8e82
BA
535 {addTime: data.addTime, initime: data.initime}
536 );
a0c41e7e 537 }
6808d7a1
BA
538 if (data.drawSent) this.drawOffer = "received";
539 if (data.score != "*") {
a0c41e7e 540 this.drawOffer = "";
6808d7a1 541 if (this.game.score == "*") this.gameOver(data.score);
760adbce
BA
542 }
543 },
dcd68c41 544 clickDraw: function() {
6808d7a1
BA
545 if (!this.game.mycolor) return; //I'm just spectator
546 if (["received", "threerep"].includes(this.drawOffer)) {
547 if (!confirm(this.st.tr["Accept draw?"])) return;
548 const message =
549 this.drawOffer == "received"
550 ? "Mutual agreement"
551 : "Three repetitions";
552 this.send("draw", { data: message });
77c50966 553 this.gameOver("1/2", message);
6808d7a1 554 } else if (this.drawOffer == "") {
e71161fb 555 // No effect if drawOffer == "sent"
9ee2826a 556 if (this.game.mycolor != this.vr.turn) {
6808d7a1 557 alert(this.st.tr["Draw offer only in your turn"]);
6fba6e0c 558 return;
6808d7a1
BA
559 }
560 if (!confirm(this.st.tr["Offer draw?"])) return;
760adbce 561 this.drawOffer = "sent";
71468011 562 this.send("drawoffer");
6808d7a1 563 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
a6088c90
BA
564 }
565 },
7f3484bd 566 abortGame: function() {
6808d7a1 567 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
8477e53d 568 this.gameOver("?", "Stop");
71468011 569 this.send("abort");
a6088c90 570 },
6808d7a1 571 resign: function() {
77c50966 572 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
a6088c90 573 return;
6808d7a1 574 this.send("resign", { data: this.game.mycolor });
8477e53d
BA
575 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
576 const side = this.game.mycolor == "w" ? "White" : "Black";
577 this.gameOver(score, side + " surrender");
a6088c90 578 },
967a2686
BA
579 // 3 cases for loading a game:
580 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
581 // - from server (one correspondance game I play[ed] or not)
582 // - from remote peer (one live game I don't play, finished or not)
760adbce 583 loadGame: function(game, callback) {
6808d7a1 584 const afterRetrieval = async game => {
f41ce580
BA
585 const vModule = await import("@/variants/" + game.vname + ".js");
586 window.V = vModule.VariantRules;
587 this.vr = new V(game.fen);
6808d7a1 588 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
71468011 589 const tc = extractTime(game.cadence);
9ef63965
BA
590 const myIdx = game.players.findIndex(p => {
591 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
592 });
6808d7a1
BA
593 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
594 if (!game.chats) game.chats = []; //live games don't have chat history
595 if (gtype == "corr") {
596 if (game.players[0].color == "b") {
f41ce580 597 // Adopt the same convention for live and corr games: [0] = white
6808d7a1
BA
598 [game.players[0], game.players[1]] = [
599 game.players[1],
600 game.players[0]
601 ];
f41ce580 602 }
7f3484bd 603 // NOTE: clocks in seconds, initime in milliseconds
6808d7a1 604 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
e71161fb 605 const L = game.moves.length;
6808d7a1 606 if (game.score == "*") {
e71161fb 607 // Set clocks + initime
92240cf0 608 game.clocks = [tc.mainTime, tc.mainTime];
b7cbbda1 609 game.initime = [0, 0];
92240cf0
BA
610 if (L >= 1) {
611 const gameLastupdate = game.moves[L-1].played;
612 game.initime[L % 2] = gameLastupdate;
c3d16e78
BA
613 if (L >= 2) {
614 game.clocks[L % 2] =
615 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
616 }
5f131484 617 }
92a523d1 618 }
9ef63965 619 // Sort chat messages from newest to oldest
6808d7a1
BA
620 game.chats.sort((c1, c2) => {
621 return c2.added - c1.added;
622 });
0d329b05 623 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
8477e53d 624 // Did a chat message arrive after my last move?
9ef63965 625 let dtLastMove = 0;
e71161fb
BA
626 if (L == 1 && myIdx == 0)
627 dtLastMove = game.moves[0].played;
628 else if (L >= 2) {
629 if (L % 2 == 0) {
630 // It's now white turn
631 dtLastMove = game.moves[L-1-(1-myIdx)].played;
632 } else {
633 // Black turn:
634 dtLastMove = game.moves[L-1-myIdx].played;
9ef63965
BA
635 }
636 }
637 if (dtLastMove < game.chats[0].added)
638 document.getElementById("chatBtn").classList.add("somethingnew");
639 }
640 // Now that we used idx and played, re-format moves as for live games
8477e53d 641 game.moves = game.moves.map(m => m.squares);
c0b27606 642 }
6808d7a1 643 if (gtype == "live" && game.clocks[0] < 0) {
8477e53d 644 // Game is unstarted
66d03f23 645 game.clocks = [tc.mainTime, tc.mainTime];
6808d7a1 646 if (game.score == "*") {
b7cbbda1 647 game.initime[0] = Date.now();
6808d7a1 648 if (myIdx >= 0) {
b7cbbda1 649 // I play in this live game; corr games don't have clocks+initime
6808d7a1 650 GameStorage.update(game.id, {
b7cbbda1 651 clocks: game.clocks,
6808d7a1 652 initime: game.initime
b7cbbda1
BA
653 });
654 }
22efa391 655 }
66d03f23 656 }
e8da204a 657 if (!!game.drawOffer) {
6808d7a1 658 if (game.drawOffer == "t")
8477e53d 659 // Three repetitions
77c50966 660 this.drawOffer = "threerep";
6808d7a1 661 else {
8477e53d 662 // Draw offered by any of the players:
6808d7a1 663 if (myIdx < 0) this.drawOffer = "received";
6808d7a1 664 else {
77c50966 665 // I play in this game:
6808d7a1
BA
666 if (
667 (game.drawOffer == "w" && myIdx == 0) ||
668 (game.drawOffer == "b" && myIdx == 1)
669 )
77c50966 670 this.drawOffer = "sent";
6808d7a1 671 else this.drawOffer = "received";
77c50966
BA
672 }
673 }
674 }
725da57f
BA
675 this.repeat = {}; //reset: scan past moves' FEN:
676 let repIdx = 0;
725da57f 677 let vr_tmp = new V(game.fenStart);
725da57f
BA
678 let curTurn = "n";
679 game.moves.forEach(m => {
e71161fb
BA
680 playMove(m, vr_tmp);
681 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
682 this.repeat[fenIdx] = this.repeat[fenIdx]
683 ? this.repeat[fenIdx] + 1
725da57f
BA
684 : 1;
685 });
725da57f 686 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
6808d7a1 687 this.game = Object.assign(
cf742aaf 688 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 689 {
c0b27606 690 type: gtype,
66d03f23 691 increment: tc.increment,
9ef63965 692 mycolor: mycolor,
5f131484
BA
693 // opponent sid not strictly required (or available), but easier
694 // at least oppsid or oppid is available anyway:
6808d7a1 695 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
725da57f 696 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
dcff8e82 697 addTimes: [], //used for live games
e71161fb
BA
698 },
699 game,
4b0384fa 700 );
dcff8e82
BA
701 if (this.gameIsLoading)
702 // Re-load game because we missed some moves:
57eb158f 703 // artificially reset BaseGame (required if moves arrived in wrong order)
dcff8e82 704 this.$refs["basegame"].re_setVariables();
9ef63965 705 this.re_setClocks();
a0c41e7e
BA
706 this.$nextTick(() => {
707 this.game.rendered = true;
708 // Did lastate arrive before game was rendered?
6808d7a1 709 if (this.lastate) this.processLastate();
a0c41e7e 710 });
d6f08e56
BA
711 if (this.gameIsLoading) {
712 this.gameIsLoading = false;
713 if (this.gotMoveIdx >= game.moves.length)
714 // Some moves arrived meanwhile...
715 this.askGameAgain();
716 }
dcff8e82 717 if (!!callback) callback();
967a2686 718 };
f9c36b2d 719 if (!!game) {
6808d7a1
BA
720 afterRetrieval(game);
721 return;
967a2686 722 }
6808d7a1
BA
723 if (this.gameRef.rid) {
724 // Remote live game: forgetting about callback func... (TODO: design)
725 this.send("askfullgame", { target: this.gameRef.rid });
726 } else {
f41ce580 727 // Local or corr game
8477e53d 728 // NOTE: afterRetrieval() is never called if game not found
11667c79 729 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 730 }
a6088c90 731 },
9ef63965 732 re_setClocks: function() {
dcff8e82 733 if (this.game.moves.length < 2 || this.game.score != "*") {
9ef63965 734 // 1st move not completed yet, or game over: freeze time
57eb158f 735 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
9ef63965
BA
736 return;
737 }
738 const currentTurn = this.vr.turn;
8477e53d 739 const currentMovesCount = this.game.moves.length;
6808d7a1
BA
740 const colorIdx = ["w", "b"].indexOf(currentTurn);
741 let countdown =
742 this.game.clocks[colorIdx] -
743 (Date.now() - this.game.initime[colorIdx]) / 1000;
744 this.virtualClocks = [0, 1].map(i => {
745 const removeTime =
746 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
57eb158f 747 return ppt(this.game.clocks[i] - removeTime).split(':');
9ef63965
BA
748 });
749 let clockUpdate = setInterval(() => {
6808d7a1
BA
750 if (
751 countdown < 0 ||
8477e53d 752 this.game.moves.length > currentMovesCount ||
6808d7a1
BA
753 this.game.score != "*"
754 ) {
9ef63965
BA
755 clearInterval(clockUpdate);
756 if (countdown < 0)
6808d7a1 757 this.gameOver(
8477e53d 758 currentTurn == "w" ? "0-1" : "1-0",
00c07ba3 759 "Time"
6808d7a1
BA
760 );
761 } else
762 this.$set(
763 this.virtualClocks,
764 colorIdx,
57eb158f 765 ppt(Math.max(0, --countdown)).split(':')
6808d7a1 766 );
9ef63965
BA
767 }, 1000);
768 },
57eb158f 769 // Update variables and storage after a move:
e71161fb 770 processMove: function(move, data) {
e5c1d0fb 771 if (!data) data = {};
e71161fb
BA
772 const moveCol = this.vr.turn;
773 const doProcessMove = () => {
774 const colorIdx = ["w", "b"].indexOf(moveCol);
775 const nextIdx = 1 - colorIdx;
dcff8e82
BA
776 const origMovescount = this.game.moves.length;
777 let addTime =
778 this.game.type == "live"
779 ? (data.addTime || 0)
780 : undefined;
f9c36b2d 781 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
e71161fb
BA
782 if (this.drawOffer == "received")
783 // I refuse draw
784 this.drawOffer = "";
dcff8e82 785 if (this.game.type == "live" && origMovescount >= 2) {
e71161fb
BA
786 const elapsed = Date.now() - this.game.initime[colorIdx];
787 // elapsed time is measured in milliseconds
788 addTime = this.game.increment - elapsed / 1000;
789 }
dce792f6 790 }
dcff8e82 791 // Update current game object:
e71161fb 792 playMove(move, this.vr);
f9c36b2d 793// TODO: notifyTurn: "changeturn" message
dcff8e82 794 this.game.moves.push(move);
e71161fb 795 // (add)Time indication: useful in case of lastate infos requested
dcff8e82
BA
796 if (this.game.type == "live")
797 this.game.addTimes.push(addTime);
e71161fb 798 this.game.fen = this.vr.getFen();
92240cf0
BA
799 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
800 // In corr games, just reset clock to mainTime:
801 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
e71161fb 802 // data.initime is set only when I receive a "lastate" move from opponent
e5c1d0fb 803 this.game.initime[nextIdx] = data.initime || Date.now();
e71161fb
BA
804 this.re_setClocks();
805 // If repetition detected, consider that a draw offer was received:
f9c36b2d
BA
806 const fenObj = this.vr.getFenForRepeat();
807 this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1;
808 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
e71161fb
BA
809 else if (this.drawOffer == "threerep") this.drawOffer = "";
810 // Since corr games are stored at only one location, update should be
811 // done only by one player for each move:
dcff8e82
BA
812 if (!!this.game.mycolor && !data.receiveMyMove) {
813 // NOTE: 'var' to see that variable outside this block
814 var filtered_move = getFilteredMove(move);
815 }
e71161fb 816 if (
f9c36b2d
BA
817 !!this.game.mycolor &&
818 !data.receiveMyMove &&
e71161fb
BA
819 (this.game.type == "live" || moveCol == this.game.mycolor)
820 ) {
821 let drawCode = "";
822 switch (this.drawOffer) {
823 case "threerep":
824 drawCode = "t";
825 break;
826 case "sent":
827 drawCode = this.game.mycolor;
828 break;
829 case "received":
830 drawCode = V.GetOppCol(this.game.mycolor);
831 break;
832 }
833 if (this.game.type == "corr") {
834 GameStorage.update(this.gameRef.id, {
835 fen: this.game.fen,
836 move: {
837 squares: filtered_move,
838 played: Date.now(),
dcff8e82 839 idx: origMovescount
e71161fb
BA
840 },
841 // Code "n" for "None" to force reset (otherwise it's ignored)
842 drawOffer: drawCode || "n"
843 });
844 }
57eb158f
BA
845 else {
846 const updateStorage = () => {
847 GameStorage.update(this.gameRef.id, {
848 fen: this.game.fen,
849 move: filtered_move,
850 moveIdx: origMovescount,
851 clocks: this.game.clocks,
852 initime: this.game.initime,
853 drawOffer: drawCode
854 });
855 };
856 // The active tab can update storage immediately
857 if (!document.hidden) updateStorage();
858 // Small random delay otherwise
859 else setTimeout(updateStorage, 500 + 1000 * Math.random());
e71161fb 860 }
e69f159d 861 }
dcff8e82
BA
862 // Send move ("newmove" event) to people in the room (if our turn)
863 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
864 const sendMove = {
865 move: filtered_move,
866 index: origMovescount,
867 // color is required to check if this is my move (if several tabs opened)
868 color: moveCol,
869 addTime: addTime, //undefined for corr games
870 cancelDrawOffer: this.drawOffer == ""
871 };
872 this.opponentGotMove = false;
873 this.send("newmove", {data: sendMove});
874 // If the opponent doesn't reply gotmove soon enough, re-send move:
57eb158f
BA
875 let retrySendmove = setInterval(
876 () => {
877 if (this.opponentGotMove) {
878 clearInterval(retrySendmove);
879 return;
880 }
881 let oppsid = this.game.players[nextIdx].sid;
882 if (!oppsid) {
883 oppsid = Object.keys(this.people).find(
884 sid => this.people[sid].id == this.game.players[nextIdx].uid
885 );
886 }
887 if (!oppsid || !this.people[oppsid])
888 // Opponent is disconnected: he'll ask last state
889 clearInterval(retrySendmove);
890 else this.send("newmove", {data: sendMove, target: oppsid});
891 },
892 1000
893 );
dcff8e82 894 }
e71161fb 895 };
f9c36b2d
BA
896 if (
897 this.game.type == "corr" &&
898 moveCol == this.game.mycolor &&
899 !data.receiveMyMove
900 ) {
e71161fb 901 setTimeout(() => {
f9c36b2d
BA
902 // TODO: remplacer cette confirm box par qqch de plus discret
903 // (et de même pour challenge accepté / refusé)
e71161fb
BA
904 if (
905 !confirm(
906 this.st.tr["Move played:"] +
907 " " +
908 getFullNotation(move) +
909 "\n" +
910 this.st.tr["Are you sure?"]
911 )
912 ) {
913 this.$refs["basegame"].cancelLastMove();
914 return;
915 }
916 doProcessMove();
917 // Let small time to finish drawing current move attempt:
918 }, 500);
6d68309a 919 }
e71161fb 920 else doProcessMove();
b4fb1612 921 },
430a2038 922 gameOver: function(score, scoreMsg) {
430a2038 923 this.game.score = score;
8477e53d 924 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
ab6f48ea
BA
925 const myIdx = this.game.players.findIndex(p => {
926 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
927 });
6808d7a1 928 if (myIdx >= 0) {
8477e53d 929 // OK, I play in this game
6808d7a1
BA
930 GameStorage.update(this.gameRef.id, {
931 score: score,
932 scoreMsg: scoreMsg
933 });
48ab808f 934 // Notify the score to main Hall. TODO: only one player (currently double send)
6808d7a1 935 this.send("result", { gid: this.game.id, score: score });
dcd68c41 936 }
6808d7a1
BA
937 }
938 }
a6088c90
BA
939};
940</script>
7e1a1fe9 941
41c80bb6 942<style lang="sass" scoped>
72ccbd67 943.connected
050ae3b5 944 background-color: lightgreen
72ccbd67 945
ed06d9e9
BA
946#participants
947 margin-left: 5px
948
949.anonymous
950 color: grey
951 font-style: italic
952
ec905cbc
BA
953#playersInfo > p
954 margin: 0
955
430a2038
BA
956@media screen and (min-width: 768px)
957 #actions
958 width: 300px
959@media screen and (max-width: 767px)
960 .game
961 width: 100%
72ccbd67 962
430a2038 963#actions
cf94b843 964 display: inline-block
1d6d7b1d 965 margin: 0
430a2038
BA
966 button
967 display: inline-block
430a2038 968 margin: 0
a1c48034 969
050ae3b5
BA
970@media screen and (max-width: 767px)
971 #aboveBoard
972 text-align: center
885d93a7
BA
973@media screen and (min-width: 768px)
974 #aboveBoard
975 margin-left: 30%
050ae3b5 976
2f258c37
BA
977.variant-cadence
978 padding-right: 10px
979
980.variant-name
8c5f5390 981 font-weight: bold
77c50966 982 padding-right: 10px
77c50966 983
57eb158f 984span.name
050ae3b5 985 font-size: 1.5rem
57eb158f 986 padding: 0 3px
050ae3b5 987
57eb158f 988span.time
050ae3b5
BA
989 font-size: 2rem
990 display: inline-block
57eb158f
BA
991 .time-left
992 margin-left: 10px
993 .time-right
994 margin-left: 5px
995 .time-separator
996 margin-left: 5px
997 position: relative
998 top: -1px
999
1000span.yourturn
1001 color: #831B1B
1002 .time-separator
1003 animation: blink-animation 2s steps(3, start) infinite
1004@keyframes blink-animation
1005 to
1006 visibility: hidden
050ae3b5
BA
1007
1008.split-names
1009 display: inline-block
1010 margin: 0 15px
1011
430a2038 1012#chat
a1c48034 1013 padding-top: 20px
a154d45e 1014 max-width: 767px
430a2038 1015 border: none;
cf94b843
BA
1016
1017#chatBtn
1018 margin: 0 10px 0 0
dcd68c41
BA
1019
1020.draw-sent, .draw-sent:hover
1021 background-color: lightyellow
1022
1023.draw-received, .draw-received:hover
1024 background-color: lightgreen
1025
1026.draw-threerep, .draw-threerep:hover
1027 background-color: #e4d1fc
2f258c37
BA
1028
1029.somethingnew
1030 background-color: #c5fefe
7e1a1fe9 1031</style>