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