Update TODOs
[vchess.git] / client / src / views / Game.vue
... / ...
CommitLineData
1<template lang="pug">
2main
3 input#modalChat.modal(
4 type="checkbox"
5 @click="resetChatColor()"
6 )
7 div#chatWrap(
8 role="dialog"
9 data-checkbox="modalChat"
10 )
11 #chat.card
12 label.modal-close(for="modalChat")
13 #participants
14 span {{ Object.keys(people).length + " " + st.tr["participant(s):"] }}
15 span(
16 v-for="p in Object.values(people)"
17 v-if="p.name"
18 )
19 | {{ p.name }}
20 span.anonymous(v-if="Object.values(people).some(p => !p.name && p.id === 0)")
21 | + @nonymous
22 Chat(
23 :players="game.players"
24 :pastChats="game.chats"
25 :newChat="newChat"
26 @mychat="processChat"
27 @chatcleared="clearChat"
28 )
29 .row
30 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
31 span.variant-cadence {{ game.cadence }}
32 span.variant-name {{ game.vname }}
33 button#chatBtn(onClick="window.doClick('modalChat')") Chat
34 #actions(v-if="game.score=='*'")
35 button(
36 @click="clickDraw()"
37 :class="{['draw-' + drawOffer]: true}"
38 )
39 | {{ st.tr["Draw"] }}
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"] }}
50 #playersInfo
51 p
52 span.name(:class="{connected: isConnected(0)}")
53 | {{ game.players[0].name || "@nonymous" }}
54 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
55 span.split-names -
56 span.name(:class="{connected: isConnected(1)}")
57 | {{ game.players[1].name || "@nonymous" }}
58 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
59 BaseGame(
60 ref="basegame"
61 :game="game"
62 @newmove="processMove"
63 @gameover="gameOver"
64 )
65</template>
66
67<script>
68import BaseGame from "@/components/BaseGame.vue";
69import Chat from "@/components/Chat.vue";
70import { store } from "@/store";
71import { GameStorage } from "@/utils/gameStorage";
72import { ppt } from "@/utils/datetime";
73import { ajax } from "@/utils/ajax";
74import { extractTime } from "@/utils/timeControl";
75import { getRandString } from "@/utils/alea";
76import { processModalClick } from "@/utils/modalClick";
77import { getFullNotation } from "@/utils/notation";
78import { playMove, getFilteredMove } from "@/utils/playUndo";
79import { getScoreMessage } from "@/utils/scoring";
80import { ArrayFun } from "@/utils/array";
81import params from "@/parameters";
82export default {
83 name: "my-game",
84 components: {
85 BaseGame,
86 Chat
87 },
88 // gameRef: to find the game in (potentially remote) storage
89 data: function() {
90 return {
91 st: store.state,
92 gameRef: {
93 // rid = remote (socket) ID
94 id: "",
95 rid: ""
96 },
97 game: {
98 // Passed to BaseGame
99 players: [{ name: "" }, { name: "" }],
100 chats: [],
101 rendered: false
102 },
103 virtualClocks: [0, 0], //initialized with true game.clocks
104 vr: null, //"variant rules" object initialized from FEN
105 drawOffer: "",
106 people: {}, //players + observers
107 onMygames: [], //opponents (or me) on "MyGames" page
108 lastate: undefined, //used if opponent send lastate before game is ready
109 repeat: {}, //detect position repetition
110 newChat: "",
111 conn: null,
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,
119 connexionString: "",
120 // Related to (killing of) self multi-connects:
121 newConnect: {},
122 killed: {}
123 };
124 },
125 watch: {
126 $route: function(to) {
127 this.gameRef.id = to.params["id"];
128 this.gameRef.rid = to.query["rid"];
129 this.loadGame();
130 }
131 },
132 // NOTE: some redundant code with Hall.vue (mostly related to people array)
133 created: function() {
134 // Always add myself to players' list
135 const my = this.st.user;
136 this.$set(this.people, my.sid, { id: my.id, name: my.name });
137 this.gameRef.id = this.$route.params["id"];
138 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
139 // Initialize connection
140 this.connexionString =
141 params.socketUrl +
142 "/?sid=" +
143 this.st.user.sid +
144 "&tmpId=" +
145 getRandString() +
146 "&page=" +
147 encodeURIComponent(this.$route.path);
148 this.conn = new WebSocket(this.connexionString);
149 this.conn.onmessage = this.socketMessageListener;
150 this.conn.onclose = this.socketCloseListener;
151 // Socket init required before loading remote game:
152 const socketInit = callback => {
153 if (!!this.conn && this.conn.readyState == 1)
154 // 1 == OPEN state
155 callback();
156 else
157 // Socket not ready yet (initial loading)
158 // NOTE: it's important to call callback without arguments,
159 // otherwise first arg is Websocket object and loadGame fails.
160 this.conn.onopen = () => callback();
161 };
162 if (!this.gameRef.rid)
163 // Game stored locally or on server
164 this.loadGame(null, () => socketInit(this.roomInit));
165 else
166 // Game stored remotely: need socket to retrieve it
167 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
168 // --> It will be given when receiving "fullgame" socket event.
169 socketInit(this.loadGame);
170 },
171 mounted: function() {
172 document
173 .getElementById("chatWrap")
174 .addEventListener("click", processModalClick);
175 },
176 beforeDestroy: function() {
177 this.send("disconnect");
178 },
179 methods: {
180 roomInit: function() {
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 }
190 },
191 send: function(code, obj) {
192 if (!!this.conn)
193 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
194 },
195 isConnected: function(index) {
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)
199 return true;
200 // Try to find a match in people:
201 return (
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 )
211 );
212 },
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)
225 if (this.game.type == "corr") {
226 if (!!this.game.mycolor)
227 ajax("/chats", "DELETE", {gid: this.game.id});
228 this.game.chats = [];
229 }
230 },
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 },
249 socketMessageListener: function(msg) {
250 if (!this.conn) return;
251 const data = JSON.parse(msg.data);
252 switch (data.code) {
253 case "pollclients":
254 data.sockIds.forEach(sid => {
255 if (sid != this.st.user.sid) {
256 this.send("askidentity", { target: sid });
257 // Ask potentially missed last state, if opponent and I play
258 if (
259 !!this.game.mycolor &&
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 });
265 }
266 }
267 });
268 break;
269 case "connect":
270 if (!this.people[data.from]) {
271 this.newConnect[data.from] = true; //for self multi-connects tests
272 this.send("askidentity", { target: data.from });
273 }
274 break;
275 case "disconnect":
276 this.$delete(this.people, data.from);
277 break;
278 case "mconnect": {
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;
294 case "killed":
295 // I logged in elsewhere:
296 this.conn = null;
297 alert(this.st.tr["New connexion detected: tab now offline"]);
298 break;
299 case "askidentity": {
300 // Request for identification
301 const me = {
302 // Decompose to avoid revealing email
303 name: this.st.user.name,
304 sid: this.st.user.sid,
305 id: this.st.user.id
306 };
307 this.send("identity", { data: me, target: data.from });
308 break;
309 }
310 case "identity": {
311 const user = data.data;
312 this.$set(this.people, user.sid, { name: user.name, id: user.id });
313 // If I multi-connect, kill current connexion if no mark (I'm older)
314 if (this.newConnect[user.sid]) {
315 if (
316 user.id > 0 &&
317 user.id == this.st.user.id &&
318 user.sid != this.st.user.sid &&
319 !this.killed[this.st.user.sid]
320 ) {
321 this.send("killme", { sid: this.st.user.sid });
322 this.killed[this.st.user.sid] = true;
323 }
324 delete this.newConnect[user.sid];
325 }
326 break;
327 }
328 case "askgame":
329 // Send current (live) game if not asked by any of the players
330 if (
331 this.game.type == "live" &&
332 this.game.players.every(p => p.sid != data.from[0])
333 ) {
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,
341 rid: this.st.user.sid //useful in Hall if I'm an observer
342 };
343 this.send("game", { data: myGame, target: data.from });
344 }
345 break;
346 case "askfullgame":
347 this.send("fullgame", { data: this.game, target: data.from });
348 break;
349 case "fullgame":
350 // Callback "roomInit" to poll clients only after game is loaded
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);
356 break;
357 case "asklastate":
358 // Sending last state if I played a move or score != "*"
359 if (
360 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
361 this.game.score != "*" ||
362 this.drawOffer == "sent"
363 ) {
364 // Send our "last state" informations to opponent
365 const L = this.game.moves.length;
366 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
367 const myLastate = {
368 // NOTE: lastMove (when defined) includes addTime
369 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
370 // Since we played a move (or abort or resign),
371 // only drawOffer=="sent" is possible
372 drawSent: this.drawOffer == "sent",
373 score: this.game.score,
374 movesCount: L,
375 initime: this.game.initime[1 - myIdx] //relevant only if I played
376 };
377 this.send("lastate", { data: myLastate, target: data.from });
378 }
379 break;
380 case "lastate": //got opponent infos about last move
381 this.lastate = data.data;
382 if (this.game.rendered)
383 // Game is rendered (Board component)
384 this.processLastate();
385 // Else: will be processed when game is ready
386 break;
387 case "newmove": {
388 const move = data.data;
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 }
437 }
438 break;
439 }
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
449 case "resign":
450 const score = data.side == "b" ? "1-0" : "0-1";
451 const side = data.side == "w" ? "White" : "Black";
452 this.gameOver(score, side + " surrender");
453 break;
454 case "abort":
455 this.gameOver("?", "Stop");
456 break;
457 case "draw":
458 this.gameOver("1/2", data.data);
459 break;
460 case "drawoffer":
461 // NOTE: observers don't know who offered draw
462 this.drawOffer = "received";
463 break;
464 case "newchat":
465 this.newChat = data.data;
466 if (!document.getElementById("modalChat").checked)
467 document.getElementById("chatBtn").classList.add("somethingnew");
468 break;
469 }
470 },
471 socketCloseListener: function() {
472 this.conn = new WebSocket(this.connexionString);
473 this.conn.addEventListener("message", this.socketMessageListener);
474 this.conn.addEventListener("close", this.socketCloseListener);
475 },
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;
481 if (data.movesCount > L) {
482 // Just got last move from him
483 this.$refs["basegame"].play(
484 data.lastMove.move,
485 "received",
486 null,
487 {addTime: data.lastMove.addTime, initime: data.initime});
488 }
489 if (data.drawSent) this.drawOffer = "received";
490 if (data.score != "*") {
491 this.drawOffer = "";
492 if (this.game.score == "*") this.gameOver(data.score);
493 }
494 },
495 clickDraw: function() {
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 });
504 this.gameOver("1/2", message);
505 } else if (this.drawOffer == "") {
506 // No effect if drawOffer == "sent"
507 if (!!this.game.mycolor != this.vr.turn) {
508 alert(this.st.tr["Draw offer only in your turn"]);
509 return;
510 }
511 if (!confirm(this.st.tr["Offer draw?"])) return;
512 this.drawOffer = "sent";
513 this.send("drawoffer");
514 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
515 }
516 },
517 abortGame: function() {
518 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
519 this.gameOver("?", "Stop");
520 this.send("abort");
521 },
522 resign: function() {
523 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
524 return;
525 this.send("resign", { data: this.game.mycolor });
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");
529 },
530 // 3 cases for loading a game:
531 // - from indexedDB (running or completed live game I play)
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)
534 loadGame: function(game, callback) {
535 const afterRetrieval = async game => {
536 const vModule = await import("@/variants/" + game.vname + ".js");
537 window.V = vModule.VariantRules;
538 this.vr = new V(game.fen);
539 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
540 const tc = extractTime(game.cadence);
541 const myIdx = game.players.findIndex(p => {
542 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
543 });
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") {
548 // Adopt the same convention for live and corr games: [0] = white
549 [game.players[0], game.players[1]] = [
550 game.players[1],
551 game.players[0]
552 ];
553 }
554 // NOTE: clocks in seconds, initime in milliseconds
555 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
556 const L = game.moves.length;
557 if (game.score == "*") {
558 // Set clocks + initime
559 game.clocks = [tc.mainTime, tc.mainTime];
560 game.initime = [0, 0];
561 if (L >= 1) {
562 const gameLastupdate = game.moves[L-1].played;
563 game.initime[L % 2] = gameLastupdate;
564 if (L >= 2) {
565 game.clocks[L % 2] =
566 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
567 }
568 }
569 }
570 // Sort chat messages from newest to oldest
571 game.chats.sort((c1, c2) => {
572 return c2.added - c1.added;
573 });
574 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
575 // Did a chat message arrive after my last move?
576 let dtLastMove = 0;
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;
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
592 game.moves = game.moves.map(m => m.squares);
593 }
594 if (gtype == "live" && game.clocks[0] < 0) {
595 // Game is unstarted
596 game.clocks = [tc.mainTime, tc.mainTime];
597 if (game.score == "*") {
598 game.initime[0] = Date.now();
599 if (myIdx >= 0) {
600 // I play in this live game; corr games don't have clocks+initime
601 GameStorage.update(game.id, {
602 clocks: game.clocks,
603 initime: game.initime
604 });
605 }
606 }
607 }
608 if (game.drawOffer) {
609 if (game.drawOffer == "t")
610 // Three repetitions
611 this.drawOffer = "threerep";
612 else {
613 // Draw offered by any of the players:
614 if (myIdx < 0) this.drawOffer = "received";
615 else {
616 // I play in this game:
617 if (
618 (game.drawOffer == "w" && myIdx == 0) ||
619 (game.drawOffer == "b" && myIdx == 1)
620 )
621 this.drawOffer = "sent";
622 else this.drawOffer = "received";
623 }
624 }
625 }
626 this.repeat = {}; //reset: scan past moves' FEN:
627 let repIdx = 0;
628 let vr_tmp = new V(game.fenStart);
629 let curTurn = "n";
630 game.moves.forEach(m => {
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
635 : 1;
636 });
637 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
638 this.game = Object.assign(
639 // NOTE: assign mycolor here, since BaseGame could also be VS computer
640 {
641 type: gtype,
642 increment: tc.increment,
643 mycolor: mycolor,
644 // opponent sid not strictly required (or available), but easier
645 // at least oppsid or oppid is available anyway:
646 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
647 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
648 movesCount: game.moves.length
649 },
650 game,
651 );
652 if (this.fullGameRequested)
653 // Second (or more) time the full game is asked:
654 this.fullGameRequested = false;
655 this.re_setClocks();
656 this.$nextTick(() => {
657 this.game.rendered = true;
658 // Did lastate arrive before game was rendered?
659 if (this.lastate) this.processLastate();
660 });
661 if (callback) callback();
662 };
663 if (!!game) {
664 afterRetrieval(game);
665 return;
666 }
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 {
671 // Local or corr game
672 // NOTE: afterRetrieval() is never called if game not found
673 GameStorage.get(this.gameRef.id, afterRetrieval);
674 }
675 },
676 re_setClocks: function() {
677 if (this.game.movesCount < 2 || this.game.score != "*") {
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;
683 const currentMovesCount = this.game.moves.length;
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;
691 return ppt(this.game.clocks[i] - removeTime);
692 });
693 let clockUpdate = setInterval(() => {
694 if (
695 countdown < 0 ||
696 this.game.moves.length > currentMovesCount ||
697 this.game.score != "*"
698 ) {
699 clearInterval(clockUpdate);
700 if (countdown < 0)
701 this.gameOver(
702 currentTurn == "w" ? "0-1" : "1-0",
703 "Time"
704 );
705 } else
706 this.$set(
707 this.virtualClocks,
708 colorIdx,
709 ppt(Math.max(0, --countdown))
710 );
711 }, 1000);
712 },
713 // Post-process a (potentially partial) move (which was just played in BaseGame)
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;
719 if (!!this.game.mycolor && !data.receiveMyMove) {
720 // NOTE: 'var' to see that variable outside this block
721 var filtered_move = getFilteredMove(move);
722 }
723 // Send move ("newmove" event) to people in the room (if our turn)
724 let addTime = (data && this.game.type == "live") ? data.addTime : 0;
725 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
726 if (this.drawOffer == "received")
727 // I refuse draw
728 this.drawOffer = "";
729 // 'addTime' is irrelevant for corr games:
730 if (this.game.type == "live" && this.game.movesCount >= 2) {
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,
737 index: this.game.movesCount,
738 addTime: addTime, //undefined for corr games
739 cancelDrawOffer: this.drawOffer == ""
740 };
741 this.opponentGotMove = false;
742 this.send("newmove", { data: sendMove });
743
744// TODO: setInterval 500ms to 1s (750?) : if !gotMove (with the right index), re-send
745
746 }
747 // Update current game object (no need for moves stack):
748 playMove(move, this.vr);
749 this.game.movesCount++;
750// TODO: notifyTurn: "changeturn" message
751 // (add)Time indication: useful in case of lastate infos requested
752 this.game.moves.push(this.game.type == "live"
753 ? {move:move, addTime:addTime}
754 : move);
755 this.game.fen = this.vr.getFen();
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;
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:
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";
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 (
770 !!this.game.mycolor &&
771 !data.receiveMyMove &&
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 }
808 }
809 };
810 if (
811 this.game.type == "corr" &&
812 moveCol == this.game.mycolor &&
813 !data.receiveMyMove
814 ) {
815 setTimeout(() => {
816 // TODO: remplacer cette confirm box par qqch de plus discret
817 // (et de même pour challenge accepté / refusé)
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);
833 }
834 else doProcessMove();
835 },
836 gameOver: function(score, scoreMsg) {
837 this.game.score = score;
838 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
839 const myIdx = this.game.players.findIndex(p => {
840 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
841 });
842 if (myIdx >= 0) {
843 // OK, I play in this game
844 GameStorage.update(this.gameRef.id, {
845 score: score,
846 scoreMsg: scoreMsg
847 });
848 // Notify the score to main Hall. TODO: only one player (currently double send)
849 this.send("result", { gid: this.game.id, score: score });
850 }
851 }
852 }
853};
854</script>
855
856<style lang="sass" scoped>
857.connected
858 background-color: lightgreen
859
860#participants
861 margin-left: 5px
862
863.anonymous
864 color: grey
865 font-style: italic
866
867#playersInfo > p
868 margin: 0
869
870@media screen and (min-width: 768px)
871 #actions
872 width: 300px
873@media screen and (max-width: 767px)
874 .game
875 width: 100%
876
877#actions
878 display: inline-block
879 margin: 0
880 button
881 display: inline-block
882 margin: 0
883
884@media screen and (max-width: 767px)
885 #aboveBoard
886 text-align: center
887@media screen and (min-width: 768px)
888 #aboveBoard
889 margin-left: 30%
890
891.variant-cadence
892 padding-right: 10px
893
894.variant-name
895 font-weight: bold
896 padding-right: 10px
897
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
911#chat
912 padding-top: 20px
913 max-width: 767px
914 border: none;
915
916#chatBtn
917 margin: 0 10px 0 0
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
927
928.somethingnew
929 background-color: #c5fefe
930</style>