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