Uniformize presentation for corr move validation
[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 .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 ref="chatcomp"
24 :players="game.players"
25 :pastChats="game.chats"
26 :newChat="newChat"
27 @mychat="processChat"
28 @chatcleared="clearChat"
29 )
30 input#modalConfirm.modal(type="checkbox")
31 div#confirmDiv(role="dialog")
32 .card
33 .diagram(
34 v-if="!!vr && ['all','byrow'].includes(vr.showMoves)"
35 v-html="curDiag"
36 )
37 p.text-center(v-else)
38 span {{ st.tr["Move played:"] + " " }}
39 span.bold {{ moveNotation }}
40 br
41 span {{ st.tr["Are you sure?"] }}
42 .button-group#buttonsConfirm
43 // onClick for acceptBtn: set dynamically
44 button.acceptBtn
45 span {{ st.tr["Validate"] }}
46 button.refuseBtn(@click="cancelMove()")
47 span {{ st.tr["Cancel"] }}
48 .row
49 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
50 span.variant-cadence {{ game.cadence }}
51 span.variant-name {{ game.vname }}
52 span#nextGame(
53 v-if="nextIds.length > 0"
54 @click="showNextGame()"
55 )
56 | {{ st.tr["Next_g"] }}
57 button#chatBtn.tooltip(
58 onClick="window.doClick('modalChat')"
59 aria-label="Chat"
60 )
61 img(src="/images/icons/chat.svg")
62 #actions(v-if="game.score=='*'")
63 button.tooltip(
64 @click="clickDraw()"
65 :class="{['draw-' + drawOffer]: true}"
66 :aria-label="st.tr['Draw']"
67 )
68 img(src="/images/icons/draw.svg")
69 button.tooltip(
70 v-if="!!game.mycolor"
71 @click="abortGame()"
72 :aria-label="st.tr['Abort']"
73 )
74 img(src="/images/icons/abort.svg")
75 button.tooltip(
76 v-if="!!game.mycolor"
77 @click="resign()"
78 :aria-label="st.tr['Resign']"
79 )
80 img(src="/images/icons/resign.svg")
81 button.tooltip(
82 v-else-if="!!game.mycolor"
83 @click="rematch()"
84 :aria-label="st.tr['Rematch']"
85 )
86 img(src="/images/icons/rematch.svg")
87 #playersInfo
88 p
89 span.name(:class="{connected: isConnected(0)}")
90 | {{ game.players[0].name || "@nonymous" }}
91 span.time(
92 v-if="game.score=='*'"
93 :class="{yourturn: !!vr && vr.turn == 'w'}"
94 )
95 span.time-left {{ virtualClocks[0][0] }}
96 span.time-separator(v-if="!!virtualClocks[0][1]") :
97 span.time-right(v-if="!!virtualClocks[0][1]")
98 | {{ virtualClocks[0][1] }}
99 span.split-names -
100 span.name(:class="{connected: isConnected(1)}")
101 | {{ game.players[1].name || "@nonymous" }}
102 span.time(
103 v-if="game.score=='*'"
104 :class="{yourturn: !!vr && vr.turn == 'b'}"
105 )
106 span.time-left {{ virtualClocks[1][0] }}
107 span.time-separator(v-if="!!virtualClocks[1][1]") :
108 span.time-right(v-if="!!virtualClocks[1][1]")
109 | {{ virtualClocks[1][1] }}
110 BaseGame(
111 ref="basegame"
112 :game="game"
113 @newmove="processMove"
114 )
115</template>
116
117<script>
118import BaseGame from "@/components/BaseGame.vue";
119import Chat from "@/components/Chat.vue";
120import { store } from "@/store";
121import { GameStorage } from "@/utils/gameStorage";
122import { ppt } from "@/utils/datetime";
123import { ajax } from "@/utils/ajax";
124import { extractTime } from "@/utils/timeControl";
125import { getRandString } from "@/utils/alea";
126import { getScoreMessage } from "@/utils/scoring";
127import { getFullNotation } from "@/utils/notation";
128import { getDiagram } from "@/utils/printDiagram";
129import { processModalClick } from "@/utils/modalClick";
130import { playMove, getFilteredMove } from "@/utils/playUndo";
131import { ArrayFun } from "@/utils/array";
132import params from "@/parameters";
133export default {
134 name: "my-game",
135 components: {
136 BaseGame,
137 Chat
138 },
139 data: function() {
140 return {
141 st: store.state,
142 gameRef: {
143 // rid = remote (socket) ID
144 id: "",
145 rid: ""
146 },
147 nextIds: [],
148 game: {}, //passed to BaseGame
149 // virtualClocks will be initialized from true game.clocks
150 virtualClocks: [],
151 vr: null, //"variant rules" object initialized from FEN
152 drawOffer: "",
153 people: {}, //players + observers
154 onMygames: [], //opponents (or me) on "MyGames" page
155 lastate: undefined, //used if opponent send lastate before game is ready
156 repeat: {}, //detect position repetition
157 curDiag: "", //for corr moves confirmation
158 newChat: "",
159 conn: null,
160 roomInitialized: false,
161 // If newmove has wrong index: ask fullgame again:
162 askGameTime: 0,
163 gameIsLoading: false,
164 // If asklastate got no reply, ask again:
165 gotLastate: false,
166 gotMoveIdx: -1, //last move index received
167 // If newmove got no pingback, send again:
168 opponentGotMove: false,
169 connexionString: "",
170 // Incomplete info games: show move played
171 moveNotation: "",
172 // Intervals from setInterval():
173 askLastate: null,
174 retrySendmove: null,
175 clockUpdate: null,
176 // Related to (killing of) self multi-connects:
177 newConnect: {},
178 killed: {}
179 };
180 },
181 watch: {
182 $route: function(to, from) {
183 if (from.params["id"] != to.params["id"]) {
184 // Change everything:
185 this.cleanBeforeDestroy();
186 let boardDiv = document.querySelector(".game");
187 if (!!boardDiv)
188 // In case of incomplete information variant:
189 boardDiv.style.visibility = "hidden";
190 this.atCreation();
191 } else {
192 // Same game ID
193 this.gameRef.id = to.params["id"];
194 this.gameRef.rid = to.query["rid"];
195 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
196 this.loadGame();
197 }
198 }
199 },
200 // NOTE: some redundant code with Hall.vue (mostly related to people array)
201 created: function() {
202 this.atCreation();
203 },
204 mounted: function() {
205 document
206 .getElementById("chatWrap")
207 .addEventListener("click", processModalClick);
208 if ("ontouchstart" in window) {
209 // Disable tooltips on smartphones:
210 document.getElementsByClassName("tooltip").forEach(elt => {
211 elt.classList.remove("tooltip");
212 });
213 }
214 },
215 beforeDestroy: function() {
216 this.cleanBeforeDestroy();
217 },
218 methods: {
219 atCreation: function() {
220 // 0] (Re)Set variables
221 this.gameRef.id = this.$route.params["id"];
222 // rid = remote ID to find an observed live game,
223 // next = next corr games IDs to navigate faster
224 // (Both might be undefined)
225 this.gameRef.rid = this.$route.query["rid"];
226 this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
227 // Always add myself to players' list
228 const my = this.st.user;
229 this.$set(this.people, my.sid, { id: my.id, name: my.name });
230 this.game = {
231 players: [{ name: "" }, { name: "" }],
232 chats: [],
233 rendered: false
234 };
235 let chatComp = this.$refs["chatcomp"];
236 if (!!chatComp) chatComp.chats = [];
237 this.virtualClocks = [[0,0], [0,0]];
238 this.vr = null;
239 this.drawOffer = "";
240 this.onMygames = [];
241 this.lastate = undefined;
242 this.newChat = "";
243 this.roomInitialized = false;
244 this.askGameTime = 0;
245 this.gameIsLoading = false;
246 this.gotLastate = false;
247 this.gotMoveIdx = -1;
248 this.opponentGotMove = false;
249 this.askLastate = null;
250 this.retrySendmove = null;
251 this.clockUpdate = null;
252 this.newConnect = {};
253 this.killed = {};
254 // 1] Initialize connection
255 this.connexionString =
256 params.socketUrl +
257 "/?sid=" +
258 this.st.user.sid +
259 "&tmpId=" +
260 getRandString() +
261 "&page=" +
262 // Discard potential "/?next=[...]" for page indication:
263 encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
264 this.conn = new WebSocket(this.connexionString);
265 this.conn.onmessage = this.socketMessageListener;
266 this.conn.onclose = this.socketCloseListener;
267 // Socket init required before loading remote game:
268 const socketInit = callback => {
269 if (!!this.conn && this.conn.readyState == 1)
270 // 1 == OPEN state
271 callback();
272 else
273 // Socket not ready yet (initial loading)
274 // NOTE: it's important to call callback without arguments,
275 // otherwise first arg is Websocket object and loadGame fails.
276 this.conn.onopen = () => callback();
277 };
278 if (!this.gameRef.rid)
279 // Game stored locally or on server
280 this.loadGame(null, () => socketInit(this.roomInit));
281 else
282 // Game stored remotely: need socket to retrieve it
283 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
284 // --> It will be given when receiving "fullgame" socket event.
285 socketInit(this.loadGame);
286 },
287 cleanBeforeDestroy: function() {
288 if (!!this.askLastate)
289 clearInterval(this.askLastate);
290 if (!!this.retrySendmove)
291 clearInterval(this.retrySendmove);
292 if (!!this.clockUpdate)
293 clearInterval(this.clockUpdate);
294 this.send("disconnect");
295 },
296 roomInit: function() {
297 if (!this.roomInitialized) {
298 // Notify the room only now that I connected, because
299 // messages might be lost otherwise (if game loading is slow)
300 this.send("connect");
301 this.send("pollclients");
302 // We may ask fullgame several times if some moves are lost,
303 // but room should be init only once:
304 this.roomInitialized = true;
305 }
306 },
307 send: function(code, obj) {
308 if (!!this.conn)
309 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
310 },
311 isConnected: function(index) {
312 const player = this.game.players[index];
313 // Is it me ?
314 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
315 // Still have to check for name (because of potential multi-accounts
316 // on same browser, although this should be rare...)
317 return (!this.st.user.name || this.st.user.name == player.name);
318 // Try to find a match in people:
319 return (
320 (
321 player.sid &&
322 Object.keys(this.people).some(sid => sid == player.sid)
323 )
324 ||
325 (
326 player.uid &&
327 Object.values(this.people).some(p => p.id == player.uid)
328 )
329 );
330 },
331 resetChatColor: function() {
332 // TODO: this is called twice, once on opening an once on closing
333 document.getElementById("chatBtn").classList.remove("somethingnew");
334 },
335 processChat: function(chat) {
336 this.send("newchat", { data: chat });
337 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
338 if (this.game.type == "corr" && this.st.user.id > 0)
339 this.updateCorrGame({ chat: chat });
340 },
341 clearChat: function() {
342 // Nothing more to do if game is live (chats not recorded)
343 if (this.game.type == "corr") {
344 if (!!this.game.mycolor) {
345 ajax(
346 "/chats",
347 "DELETE",
348 { data: { gid: this.game.id } }
349 );
350 }
351 this.$set(this.game, "chats", []);
352 }
353 },
354 // Notify turn after a new move (to opponent and me on MyGames page)
355 notifyTurn: function(sid) {
356 const player = this.people[sid];
357 const colorIdx = this.game.players.findIndex(
358 p => p.sid == sid || p.uid == player.id);
359 const color = ["w","b"][colorIdx];
360 const movesCount = this.game.moves.length;
361 const yourTurn =
362 (color == "w" && movesCount % 2 == 0) ||
363 (color == "b" && movesCount % 2 == 1);
364 this.send("turnchange", { target: sid, yourTurn: yourTurn });
365 },
366 showNextGame: function() {
367 // Did I play in current game? If not, add it to nextIds list
368 if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
369 this.nextIds.unshift(this.game.id);
370 const nextGid = this.nextIds.pop();
371 this.$router.push(
372 "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
373 },
374 rematch: function() {
375 alert("Unimplemented yet (soon :) )");
376 // TODO: same logic as for draw, but re-click remove rematch offer (toggle)
377 },
378 askGameAgain: function() {
379 this.gameIsLoading = true;
380 const currentUrl = document.location.href;
381 const doAskGame = () => {
382 if (document.location.href != currentUrl) return; //page change
383 if (!this.gameRef.rid)
384 // This is my game: just reload.
385 this.loadGame();
386 else
387 // Just ask fullgame again (once!), this is much simpler.
388 // If this fails, the user could just reload page :/
389 this.send("askfullgame", { target: this.gameRef.rid });
390 };
391 // Delay of at least 2s between two game requests
392 const now = Date.now();
393 const delay = Math.max(2000 - (now - this.askGameTime), 0);
394 this.askGameTime = now;
395 setTimeout(doAskGame, delay);
396 },
397 socketMessageListener: function(msg) {
398 if (!this.conn) return;
399 const data = JSON.parse(msg.data);
400 switch (data.code) {
401 case "pollclients":
402 data.sockIds.forEach(sid => {
403 if (sid != this.st.user.sid)
404 this.send("askidentity", { target: sid });
405 });
406 break;
407 case "connect":
408 if (!this.people[data.from]) {
409 this.newConnect[data.from] = true; //for self multi-connects tests
410 this.send("askidentity", { target: data.from });
411 }
412 break;
413 case "disconnect":
414 this.$delete(this.people, data.from);
415 break;
416 case "mconnect": {
417 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
418 // Either me (another tab) or opponent
419 const sid = data.from;
420 if (!this.onMygames.some(s => s == sid))
421 {
422 this.onMygames.push(sid);
423 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
424 }
425 break;
426 if (!this.people[sid])
427 this.send("askidentity", { target: sid });
428 }
429 case "mdisconnect":
430 ArrayFun.remove(this.onMygames, sid => sid == data.from);
431 break;
432 case "killed":
433 // I logged in elsewhere:
434 this.conn = null;
435 alert(this.st.tr["New connexion detected: tab now offline"]);
436 break;
437 case "askidentity": {
438 // Request for identification
439 const me = {
440 // Decompose to avoid revealing email
441 name: this.st.user.name,
442 sid: this.st.user.sid,
443 id: this.st.user.id
444 };
445 this.send("identity", { data: me, target: data.from });
446 break;
447 }
448 case "identity": {
449 const user = data.data;
450 this.$set(this.people, user.sid, { name: user.name, id: user.id });
451 // If I multi-connect, kill current connexion if no mark (I'm older)
452 if (this.newConnect[user.sid]) {
453 if (
454 user.id > 0 &&
455 user.id == this.st.user.id &&
456 user.sid != this.st.user.sid &&
457 !this.killed[this.st.user.sid]
458 ) {
459 this.send("killme", { sid: this.st.user.sid });
460 this.killed[this.st.user.sid] = true;
461 }
462 delete this.newConnect[user.sid];
463 }
464 if (!this.killed[this.st.user.sid]) {
465 // Ask potentially missed last state, if opponent and I play
466 if (
467 !!this.game.mycolor &&
468 this.game.type == "live" &&
469 this.game.score == "*" &&
470 this.game.players.some(p => p.sid == user.sid)
471 ) {
472 this.send("asklastate", { target: user.sid });
473 let counter = 1;
474 this.askLastate = setInterval(
475 () => {
476 // Ask at most 3 times:
477 // if no reply after that there should be a network issue.
478 if (
479 counter < 3 &&
480 !this.gotLastate &&
481 !!this.people[user.sid]
482 ) {
483 this.send("asklastate", { target: user.sid });
484 counter++;
485 } else {
486 clearInterval(this.askLastate);
487 }
488 },
489 1500
490 );
491 }
492 }
493 break;
494 }
495 case "askgame":
496 // Send current (live) game if not asked by any of the players
497 if (
498 this.game.type == "live" &&
499 this.game.players.every(p => p.sid != data.from[0])
500 ) {
501 const myGame = {
502 id: this.game.id,
503 fen: this.game.fen,
504 players: this.game.players,
505 vid: this.game.vid,
506 cadence: this.game.cadence,
507 score: this.game.score,
508 rid: this.st.user.sid //useful in Hall if I'm an observer
509 };
510 this.send("game", { data: myGame, target: data.from });
511 }
512 break;
513 case "askfullgame":
514 const gameToSend = Object.keys(this.game)
515 .filter(k =>
516 [
517 "id","fen","players","vid","cadence","fenStart","vname",
518 "moves","clocks","initime","score","drawOffer"
519 ].includes(k))
520 .reduce(
521 (obj, k) => {
522 obj[k] = this.game[k];
523 return obj;
524 },
525 {}
526 );
527 this.send("fullgame", { data: gameToSend, target: data.from });
528 break;
529 case "fullgame":
530 // Callback "roomInit" to poll clients only after game is loaded
531 this.loadGame(data.data, this.roomInit);
532 break;
533 case "asklastate":
534 // Sending informative last state if I played a move or score != "*"
535 if (
536 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
537 this.game.score != "*" ||
538 this.drawOffer == "sent"
539 ) {
540 // Send our "last state" informations to opponent
541 const L = this.game.moves.length;
542 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
543 const myLastate = {
544 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
545 clock: this.game.clocks[myIdx],
546 // Since we played a move (or abort or resign),
547 // only drawOffer=="sent" is possible
548 drawSent: this.drawOffer == "sent",
549 score: this.game.score,
550 score: this.game.scoreMsg,
551 movesCount: L,
552 initime: this.game.initime[1 - myIdx] //relevant only if I played
553 };
554 this.send("lastate", { data: myLastate, target: data.from });
555 } else {
556 this.send("lastate", { data: {nothing: true}, target: data.from });
557 }
558 break;
559 case "lastate": {
560 // Got opponent infos about last move
561 this.gotLastate = true;
562 if (!data.data.nothing) {
563 this.lastate = data.data;
564 if (this.game.rendered)
565 // Game is rendered (Board component)
566 this.processLastate();
567 // Else: will be processed when game is ready
568 }
569 break;
570 }
571 case "newmove": {
572 const movePlus = data.data;
573 const movesCount = this.game.moves.length;
574 if (movePlus.index > movesCount) {
575 // This can only happen if I'm an observer and missed a move.
576 if (this.gotMoveIdx < movePlus.index)
577 this.gotMoveIdx = movePlus.index;
578 if (!this.gameIsLoading) this.askGameAgain();
579 }
580 else {
581 if (
582 movePlus.index < movesCount ||
583 this.gotMoveIdx >= movePlus.index
584 ) {
585 // Opponent re-send but we already have the move:
586 // (maybe he didn't receive our pingback...)
587 this.send("gotmove", {data: movePlus.index, target: data.from});
588 } else {
589 this.gotMoveIdx = movePlus.index;
590 const receiveMyMove = (movePlus.color == this.game.mycolor);
591 if (!receiveMyMove && !!this.game.mycolor)
592 // Notify opponent that I got the move:
593 this.send("gotmove", {data: movePlus.index, target: data.from});
594 if (movePlus.cancelDrawOffer) {
595 // Opponent refuses draw
596 this.drawOffer = "";
597 // NOTE for corr games: drawOffer reset by player in turn
598 if (
599 this.game.type == "live" &&
600 !!this.game.mycolor &&
601 !receiveMyMove
602 ) {
603 GameStorage.update(this.gameRef.id, { drawOffer: "" });
604 }
605 }
606 this.$refs["basegame"].play(movePlus.move, "received", null, true);
607 this.processMove(
608 movePlus.move,
609 {
610 clock: movePlus.clock,
611 receiveMyMove: receiveMyMove
612 }
613 );
614 }
615 }
616 break;
617 }
618 case "gotmove": {
619 this.opponentGotMove = true;
620 // Now his clock starts running:
621 const oppIdx = ['w','b'].indexOf(this.vr.turn);
622 this.game.initime[oppIdx] = Date.now();
623 this.re_setClocks();
624 break;
625 }
626 case "resign":
627 const score = data.side == "b" ? "1-0" : "0-1";
628 const side = data.side == "w" ? "White" : "Black";
629 this.gameOver(score, side + " surrender");
630 break;
631 case "abort":
632 this.gameOver("?", "Stop");
633 break;
634 case "draw":
635 this.gameOver("1/2", data.data);
636 break;
637 case "drawoffer":
638 // NOTE: observers don't know who offered draw
639 this.drawOffer = "received";
640 break;
641 case "newchat":
642 this.newChat = data.data;
643 if (!document.getElementById("modalChat").checked)
644 document.getElementById("chatBtn").classList.add("somethingnew");
645 break;
646 }
647 },
648 socketCloseListener: function() {
649 this.conn = new WebSocket(this.connexionString);
650 this.conn.addEventListener("message", this.socketMessageListener);
651 this.conn.addEventListener("close", this.socketCloseListener);
652 },
653 updateCorrGame: function(obj, callback) {
654 ajax(
655 "/games",
656 "PUT",
657 {
658 data: {
659 gid: this.gameRef.id,
660 newObj: obj
661 },
662 success: () => {
663 if (!!callback) callback();
664 }
665 }
666 );
667 },
668 // lastate was received, but maybe game wasn't ready yet:
669 processLastate: function() {
670 const data = this.lastate;
671 this.lastate = undefined; //security...
672 const L = this.game.moves.length;
673 if (data.movesCount > L) {
674 // Just got last move from him
675 this.$refs["basegame"].play(data.lastMove, "received", null, true);
676 this.processMove(data.lastMove, { clock: data.clock });
677 }
678 if (data.drawSent) this.drawOffer = "received";
679 if (data.score != "*") {
680 this.drawOffer = "";
681 if (this.game.score == "*")
682 this.gameOver(data.score, data.scoreMsg);
683 }
684 },
685 clickDraw: function() {
686 if (!this.game.mycolor) return; //I'm just spectator
687 if (["received", "threerep"].includes(this.drawOffer)) {
688 if (!confirm(this.st.tr["Accept draw?"])) return;
689 const message =
690 this.drawOffer == "received"
691 ? "Mutual agreement"
692 : "Three repetitions";
693 this.send("draw", { data: message });
694 this.gameOver("1/2", message);
695 } else if (this.drawOffer == "") {
696 // No effect if drawOffer == "sent"
697 if (this.game.mycolor != this.vr.turn) {
698 alert(this.st.tr["Draw offer only in your turn"]);
699 return;
700 }
701 if (!confirm(this.st.tr["Offer draw?"])) return;
702 this.drawOffer = "sent";
703 this.send("drawoffer");
704 if (this.game.type == "live") {
705 GameStorage.update(
706 this.gameRef.id,
707 { drawOffer: this.game.mycolor }
708 );
709 } else this.updateCorrGame({ drawOffer: this.game.mycolor });
710 }
711 },
712 abortGame: function() {
713 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
714 this.gameOver("?", "Stop");
715 this.send("abort");
716 },
717 resign: function() {
718 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
719 return;
720 this.send("resign", { data: this.game.mycolor });
721 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
722 const side = this.game.mycolor == "w" ? "White" : "Black";
723 this.gameOver(score, side + " surrender");
724 },
725 // 3 cases for loading a game:
726 // - from indexedDB (running or completed live game I play)
727 // - from server (one correspondance game I play[ed] or not)
728 // - from remote peer (one live game I don't play, finished or not)
729 loadGame: function(game, callback) {
730 const afterRetrieval = async game => {
731 const vModule = await import("@/variants/" + game.vname + ".js");
732 window.V = vModule.VariantRules;
733 this.vr = new V(game.fen);
734 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
735 const tc = extractTime(game.cadence);
736 const myIdx = game.players.findIndex(p => {
737 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
738 });
739 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
740 if (!game.chats) game.chats = []; //live games don't have chat history
741 if (gtype == "corr") {
742 if (game.players[0].color == "b") {
743 // Adopt the same convention for live and corr games: [0] = white
744 [game.players[0], game.players[1]] = [
745 game.players[1],
746 game.players[0]
747 ];
748 }
749 // NOTE: clocks in seconds, initime in milliseconds
750 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
751 game.clocks = [tc.mainTime, tc.mainTime];
752 const L = game.moves.length;
753 if (game.score == "*") {
754 // Set clocks + initime
755 game.initime = [0, 0];
756 if (L >= 1) {
757 const gameLastupdate = game.moves[L-1].played;
758 game.initime[L % 2] = gameLastupdate;
759 if (L >= 2) {
760 game.clocks[L % 2] =
761 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
762 }
763 }
764 }
765 // Sort chat messages from newest to oldest
766 game.chats.sort((c1, c2) => {
767 return c2.added - c1.added;
768 });
769 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
770 // Did a chat message arrive after my last move?
771 let dtLastMove = 0;
772 if (L == 1 && myIdx == 0)
773 dtLastMove = game.moves[0].played;
774 else if (L >= 2) {
775 if (L % 2 == 0) {
776 // It's now white turn
777 dtLastMove = game.moves[L-1-(1-myIdx)].played;
778 } else {
779 // Black turn:
780 dtLastMove = game.moves[L-1-myIdx].played;
781 }
782 }
783 if (dtLastMove < game.chats[0].added)
784 document.getElementById("chatBtn").classList.add("somethingnew");
785 }
786 // Now that we used idx and played, re-format moves as for live games
787 game.moves = game.moves.map(m => m.squares);
788 }
789 if (gtype == "live" && game.clocks[0] < 0) {
790 // Game is unstarted
791 game.clocks = [tc.mainTime, tc.mainTime];
792 if (game.score == "*") {
793 game.initime[0] = Date.now();
794 if (myIdx >= 0) {
795 // I play in this live game; corr games don't have clocks+initime
796 GameStorage.update(game.id, {
797 clocks: game.clocks,
798 initime: game.initime
799 });
800 }
801 }
802 }
803 if (!!game.drawOffer) {
804 if (game.drawOffer == "t")
805 // Three repetitions
806 this.drawOffer = "threerep";
807 else {
808 // Draw offered by any of the players:
809 if (myIdx < 0) this.drawOffer = "received";
810 else {
811 // I play in this game:
812 if (
813 (game.drawOffer == "w" && myIdx == 0) ||
814 (game.drawOffer == "b" && myIdx == 1)
815 )
816 this.drawOffer = "sent";
817 else this.drawOffer = "received";
818 }
819 }
820 }
821 this.repeat = {}; //reset: scan past moves' FEN:
822 let repIdx = 0;
823 let vr_tmp = new V(game.fenStart);
824 let curTurn = "n";
825 game.moves.forEach(m => {
826 playMove(m, vr_tmp);
827 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
828 this.repeat[fenIdx] = this.repeat[fenIdx]
829 ? this.repeat[fenIdx] + 1
830 : 1;
831 });
832 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
833 this.game = Object.assign(
834 // NOTE: assign mycolor here, since BaseGame could also be VS computer
835 {
836 type: gtype,
837 increment: tc.increment,
838 mycolor: mycolor,
839 // opponent sid not strictly required (or available), but easier
840 // at least oppsid or oppid is available anyway:
841 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
842 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
843 },
844 game,
845 );
846 if (this.gameIsLoading)
847 // Re-load game because we missed some moves:
848 // artificially reset BaseGame (required if moves arrived in wrong order)
849 this.$refs["basegame"].re_setVariables();
850 else {
851 // Initial loading:
852 this.gotMoveIdx = game.moves.length - 1;
853 // If we arrive here after 'nextGame' action, the board might be hidden
854 let boardDiv = document.querySelector(".game");
855 if (!!boardDiv && boardDiv.style.visibility == "hidden")
856 boardDiv.style.visibility = "visible";
857 }
858 this.re_setClocks();
859 this.$nextTick(() => {
860 this.game.rendered = true;
861 // Did lastate arrive before game was rendered?
862 if (this.lastate) this.processLastate();
863 });
864 if (this.gameIsLoading) {
865 this.gameIsLoading = false;
866 if (this.gotMoveIdx >= game.moves.length)
867 // Some moves arrived meanwhile...
868 this.askGameAgain();
869 }
870 if (!!callback) callback();
871 };
872 if (!!game) {
873 afterRetrieval(game);
874 return;
875 }
876 if (this.gameRef.rid) {
877 // Remote live game: forgetting about callback func... (TODO: design)
878 this.send("askfullgame", { target: this.gameRef.rid });
879 } else {
880 // Local or corr game on server.
881 // NOTE: afterRetrieval() is never called if game not found
882 const gid = this.gameRef.id;
883 if (Number.isInteger(gid) || !isNaN(parseInt(gid))) {
884 // corr games identifiers are integers
885 ajax(
886 "/games",
887 "GET",
888 {
889 data: { gid: gid },
890 success: (res) => {
891 let g = res.game;
892 g.moves.forEach(m => {
893 m.squares = JSON.parse(m.squares);
894 });
895 afterRetrieval(g);
896 }
897 }
898 );
899 }
900 else
901 // Local game
902 GameStorage.get(this.gameRef.id, afterRetrieval);
903 }
904 },
905 re_setClocks: function() {
906 if (this.game.moves.length < 2 || this.game.score != "*") {
907 // 1st move not completed yet, or game over: freeze time
908 this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':'));
909 return;
910 }
911 const currentTurn = this.vr.turn;
912 const currentMovesCount = this.game.moves.length;
913 const colorIdx = ["w", "b"].indexOf(currentTurn);
914 let countdown =
915 this.game.clocks[colorIdx] -
916 (Date.now() - this.game.initime[colorIdx]) / 1000;
917 this.virtualClocks = [0, 1].map(i => {
918 const removeTime =
919 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
920 return ppt(this.game.clocks[i] - removeTime).split(':');
921 });
922 this.clockUpdate = setInterval(
923 () => {
924 if (
925 countdown < 0 ||
926 this.game.moves.length > currentMovesCount ||
927 this.game.score != "*"
928 ) {
929 clearInterval(this.clockUpdate);
930 if (countdown < 0)
931 this.gameOver(
932 currentTurn == "w" ? "0-1" : "1-0",
933 "Time"
934 );
935 } else
936 this.$set(
937 this.virtualClocks,
938 colorIdx,
939 ppt(Math.max(0, --countdown)).split(':')
940 );
941 },
942 1000
943 );
944 },
945 // Update variables and storage after a move:
946 processMove: function(move, data) {
947 if (!data) data = {};
948 const moveCol = this.vr.turn;
949 const doProcessMove = () => {
950 const colorIdx = ["w", "b"].indexOf(moveCol);
951 const nextIdx = 1 - colorIdx;
952 const origMovescount = this.game.moves.length;
953 let addTime = 0; //for live games
954 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
955 if (this.drawOffer == "received")
956 // I refuse draw
957 this.drawOffer = "";
958 if (this.game.type == "live" && origMovescount >= 2) {
959 const elapsed = Date.now() - this.game.initime[colorIdx];
960 // elapsed time is measured in milliseconds
961 addTime = this.game.increment - elapsed / 1000;
962 }
963 }
964 // Update current game object:
965 playMove(move, this.vr);
966 // The move is played: stop clock
967 clearInterval(this.clockUpdate);
968 if (!data.score) {
969 // Received move, score has not been computed in BaseGame (!!noemit)
970 const score = this.vr.getCurrentScore();
971 if (score != "*") this.gameOver(score);
972 }
973// TODO: notifyTurn: "changeturn" message
974 this.game.moves.push(move);
975 this.game.fen = this.vr.getFen();
976 if (this.game.type == "live") {
977 if (!!data.clock) this.game.clocks[colorIdx] = data.clock;
978 else this.game.clocks[colorIdx] += addTime;
979 }
980 // In corr games, just reset clock to mainTime:
981 else {
982 this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
983 }
984 // NOTE: opponent's initime is reset after "gotmove" is received
985 if (
986 !this.game.mycolor ||
987 moveCol != this.game.mycolor ||
988 !!data.receiveMyMove
989 ) {
990 this.game.initime[nextIdx] = Date.now();
991 }
992 // If repetition detected, consider that a draw offer was received:
993 const fenObj = this.vr.getFenForRepeat();
994 this.repeat[fenObj] =
995 !!this.repeat[fenObj]
996 ? this.repeat[fenObj] + 1
997 : 1;
998 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
999 else if (this.drawOffer == "threerep") this.drawOffer = "";
1000 if (!!this.game.mycolor && !data.receiveMyMove) {
1001 // NOTE: 'var' to see that variable outside this block
1002 var filtered_move = getFilteredMove(move);
1003 }
1004 // Since corr games are stored at only one location, update should be
1005 // done only by one player for each move:
1006 if (
1007 !!this.game.mycolor &&
1008 !data.receiveMyMove &&
1009 (this.game.type == "live" || moveCol == this.game.mycolor)
1010 ) {
1011 let drawCode = "";
1012 switch (this.drawOffer) {
1013 case "threerep":
1014 drawCode = "t";
1015 break;
1016 case "sent":
1017 drawCode = this.game.mycolor;
1018 break;
1019 case "received":
1020 drawCode = V.GetOppCol(this.game.mycolor);
1021 break;
1022 }
1023 if (this.game.type == "corr") {
1024 // corr: only move, fen and score
1025 this.updateCorrGame({
1026 fen: this.game.fen,
1027 move: {
1028 squares: filtered_move,
1029 played: Date.now(),
1030 idx: origMovescount
1031 },
1032 // Code "n" for "None" to force reset (otherwise it's ignored)
1033 drawOffer: drawCode || "n"
1034 });
1035 }
1036 else {
1037 const updateStorage = () => {
1038 GameStorage.update(this.gameRef.id, {
1039 fen: this.game.fen,
1040 move: filtered_move,
1041 moveIdx: origMovescount,
1042 clocks: this.game.clocks,
1043 initime: this.game.initime,
1044 drawOffer: drawCode
1045 });
1046 };
1047 // The active tab can update storage immediately
1048 if (!document.hidden) updateStorage();
1049 // Small random delay otherwise
1050 else setTimeout(updateStorage, 500 + 1000 * Math.random());
1051 }
1052 }
1053 // Send move ("newmove" event) to people in the room (if our turn)
1054 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
1055 let sendMove = {
1056 move: filtered_move,
1057 index: origMovescount,
1058 // color is required to check if this is my move (if several tabs opened)
1059 color: moveCol,
1060 cancelDrawOffer: this.drawOffer == ""
1061 };
1062 if (this.game.type == "live")
1063 sendMove["clock"] = this.game.clocks[colorIdx];
1064 this.opponentGotMove = false;
1065 this.send("newmove", {data: sendMove});
1066 // If the opponent doesn't reply gotmove soon enough, re-send move:
1067 // Do this at most 2 times, because mpore would mean network issues,
1068 // opponent would then be expected to disconnect/reconnect.
1069 let counter = 1;
1070 const currentUrl = document.location.href;
1071 this.retrySendmove = setInterval(
1072 () => {
1073 if (
1074 counter >= 3 ||
1075 this.opponentGotMove ||
1076 document.location.href != currentUrl //page change
1077 ) {
1078 clearInterval(this.retrySendmove);
1079 return;
1080 }
1081 let oppsid = this.game.players[nextIdx].sid;
1082 if (!oppsid) {
1083 oppsid = Object.keys(this.people).find(
1084 sid => this.people[sid].id == this.game.players[nextIdx].uid
1085 );
1086 }
1087 if (!oppsid || !this.people[oppsid])
1088 // Opponent is disconnected: he'll ask last state
1089 clearInterval(this.retrySendmove);
1090 else {
1091 this.send("newmove", { data: sendMove, target: oppsid });
1092 counter++;
1093 }
1094 },
1095 1500
1096 );
1097 }
1098 else
1099 // Not my move or I'm an observer: just start other player's clock
1100 this.re_setClocks();
1101 };
1102 if (
1103 this.game.type == "corr" &&
1104 moveCol == this.game.mycolor &&
1105 !data.receiveMyMove
1106 ) {
1107 let boardDiv = document.querySelector(".game");
1108 const afterSetScore = () => {
1109 doProcessMove();
1110 if (this.st.settings.gotonext && this.nextIds.length > 0)
1111 this.showNextGame();
1112 else {
1113 // The board might have been hidden:
1114 if (boardDiv.style.visibility == "hidden")
1115 boardDiv.style.visibility = "visible";
1116 }
1117 };
1118 let el = document.querySelector("#buttonsConfirm > .acceptBtn");
1119 // We may play several moves in a row: in case of, remove listener:
1120 let elClone = el.cloneNode(true);
1121 el.parentNode.replaceChild(elClone, el);
1122 elClone.addEventListener(
1123 "click",
1124 () => {
1125 document.getElementById("modalConfirm").checked = false;
1126 if (!!data.score && data.score != "*")
1127 // Set score first
1128 this.gameOver(data.score, null, afterSetScore);
1129 else afterSetScore();
1130 }
1131 );
1132 // PlayOnBoard is enough, and more appropriate for Synchrone Chess
1133 V.PlayOnBoard(this.vr.board, move);
1134 const position = this.vr.getBaseFen();
1135 V.UndoOnBoard(this.vr.board, move);
1136 if (["all","byrow"].includes(V.ShowMoves)) {
1137 this.curDiag = getDiagram({
1138 position: position,
1139 orientation: V.CanFlip ? this.game.mycolor : "w"
1140 });
1141 } else {
1142 // Incomplete information: just ask confirmation
1143 // Hide the board, because otherwise it could reveal infos
1144 boardDiv.style.visibility = "hidden";
1145 this.moveNotation = getFullNotation(move);
1146 }
1147 document.getElementById("modalConfirm").checked = true;
1148 }
1149 else {
1150 // Normal situation
1151 if (!!data.score && data.score != "*")
1152 this.gameOver(data.score, null, doProcessMove);
1153 else doProcessMove();
1154 }
1155 },
1156 cancelMove: function() {
1157 let boardDiv = document.querySelector(".game");
1158 if (boardDiv.style.visibility == "hidden")
1159 boardDiv.style.visibility = "visible";
1160 document.getElementById("modalConfirm").checked = false;
1161 this.$refs["basegame"].cancelLastMove();
1162 },
1163 // In corr games, callback to change page only after score is set:
1164 gameOver: function(score, scoreMsg, callback) {
1165 this.game.score = score;
1166 if (!scoreMsg) scoreMsg = getScoreMessage(score);
1167 this.game.scoreMsg = scoreMsg;
1168 this.$set(this.game, "scoreMsg", scoreMsg);
1169 const myIdx = this.game.players.findIndex(p => {
1170 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
1171 });
1172 if (myIdx >= 0) {
1173 // OK, I play in this game
1174 const scoreObj = {
1175 score: score,
1176 scoreMsg: scoreMsg
1177 };
1178 if (this.game.type == "live") {
1179 GameStorage.update(this.gameRef.id, scoreObj);
1180 if (!!callback) callback();
1181 }
1182 else this.updateCorrGame(scoreObj, callback);
1183 // Notify the score to main Hall. TODO: only one player (currently double send)
1184 this.send("result", { gid: this.game.id, score: score });
1185 }
1186 else if (!!callback) callback();
1187 }
1188 }
1189};
1190</script>
1191
1192<style lang="sass" scoped>
1193.connected
1194 background-color: lightgreen
1195
1196#participants
1197 margin-left: 5px
1198
1199.anonymous
1200 color: grey
1201 font-style: italic
1202
1203#playersInfo > p
1204 margin: 0
1205
1206@media screen and (min-width: 768px)
1207 #actions
1208 width: 300px
1209@media screen and (max-width: 767px)
1210 .game
1211 width: 100%
1212
1213#actions
1214 display: inline-block
1215 margin: 0
1216
1217button
1218 display: inline-block
1219 margin: 0
1220 display: inline-flex
1221 img
1222 height: 24px
1223 display: flex
1224 @media screen and (max-width: 767px)
1225 height: 18px
1226
1227@media screen and (max-width: 767px)
1228 #aboveBoard
1229 text-align: center
1230@media screen and (min-width: 768px)
1231 #aboveBoard
1232 margin-left: 30%
1233
1234.variant-cadence
1235 padding-right: 10px
1236
1237.variant-name
1238 font-weight: bold
1239 padding-right: 10px
1240
1241span#nextGame
1242 background-color: #edda99
1243 cursor: pointer
1244 display: inline-block
1245 margin-right: 10px
1246
1247span.name
1248 font-size: 1.5rem
1249 padding: 0 3px
1250
1251span.time
1252 font-size: 2rem
1253 display: inline-block
1254 .time-left
1255 margin-left: 10px
1256 .time-right
1257 margin-left: 5px
1258 .time-separator
1259 margin-left: 5px
1260 position: relative
1261 top: -1px
1262
1263span.yourturn
1264 color: #831B1B
1265 .time-separator
1266 animation: blink-animation 2s steps(3, start) infinite
1267@keyframes blink-animation
1268 to
1269 visibility: hidden
1270
1271.split-names
1272 display: inline-block
1273 margin: 0 15px
1274
1275#chatWrap > .card
1276 padding-top: 20px
1277 max-width: 767px
1278 border: none
1279
1280#confirmDiv > .card
1281 max-width: 767px
1282 max-height: 100%
1283
1284.draw-sent, .draw-sent:hover
1285 background-color: lightyellow
1286
1287.draw-received, .draw-received:hover
1288 background-color: lightgreen
1289
1290.draw-threerep, .draw-threerep:hover
1291 background-color: #e4d1fc
1292
1293.somethingnew
1294 background-color: #c5fefe
1295
1296.diagram
1297 margin: 0 auto
1298 max-width: 400px
1299 // width: 100% required for Firefox
1300 width: 100%
1301
1302#buttonsConfirm
1303 margin: 0
1304 & > button > span
1305 width: 100%
1306 text-align: center
1307
1308button.acceptBtn
1309 background-color: lightgreen
1310button.refuseBtn
1311 background-color: red
1312</style>