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