Fix clocks update + double move effect
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90
BA
1<template lang="pug">
2.row
3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
4 input#modalEog.modal(type="checkbox")
5 div(role="dialog" aria-labelledby="eogMessage")
6 .card.smallpad.small-modal.text-center
7 label.modal-close(for="modalEog")
8 h3#eogMessage.section {{ endgameMessage }}
834c202a
BA
9 Board(:vr="vr" :last-move="lastMove" :analyze="game.mode=='analyze'"
10 :user-color="game.mycolor" :orientation="orientation"
11 :vname="game.vname" @play-move="play")
a6088c90 12 .button-group
37cdcbf3
BA
13 button(@click="() => play()") Play
14 button(@click="() => undo()") Undo
a6088c90
BA
15 button(@click="flip") Flip
16 button(@click="gotoBegin") GotoBegin
17 button(@click="gotoEnd") GotoEnd
18 #fenDiv.section-content(v-if="showFen && !!vr")
19 p#fenString.text-center {{ vr.getFen() }}
20 #pgnDiv.section-content
21 a#download(href="#")
22 .button-group
23 button#downloadBtn(@click="download") {{ st.tr["Download PGN"] }}
24 button Import game
25 //MoveList(v-if="showMoves"
26 :moves="moves" :cursor="cursor" @goto-move="gotoMove")
27</template>
28
29<script>
30import Board from "@/components/Board.vue";
31//import MoveList from "@/components/MoveList.vue";
32import { store } from "@/store";
33import { getSquareId } from "@/utils/squareId";
34
35export default {
36 name: 'my-base-game',
37 components: {
38 Board,
39 //MoveList,
40 },
bc8734ba 41 // "vr": VariantRules object, describing the game state + rules
834c202a 42 props: ["vr","game"],
a6088c90
BA
43 data: function() {
44 return {
45 st: store.state,
b7c32f1a 46 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
47 endgameMessage: "",
48 orientation: "w",
49 score: "*", //'*' means 'unfinished'
b7c32f1a 50 moves: [],
a6088c90
BA
51 cursor: -1, //index of the move just played
52 lastMove: null,
53 };
54 },
37cdcbf3 55 watch: {
834c202a
BA
56 // game initial FEN changes when a new game starts
57 "game.fenStart": function() {
4b0384fa 58 this.re_setVariables();
37cdcbf3
BA
59 },
60 },
a6088c90
BA
61 computed: {
62 showMoves: function() {
63 return true;
64 //return window.innerWidth >= 768;
65 },
66 showFen: function() {
834c202a
BA
67 return this.game.vname != "Dark" || this.score != "*";
68 },
69 analyze: function() {
70 return this.game.mode == "analyze";
a6088c90
BA
71 },
72 },
4b0384fa
BA
73 created: function() {
74 if (!!this.game.fenStart)
75 this.re_setVariables();
76 },
a6088c90 77 methods: {
4b0384fa
BA
78 re_setVariables: function() {
79 this.endgameMessage = "";
80 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
81 this.score = this.game.score || "*"; //mutable (if initially "*")
82 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
83 const L = this.moves.length;
84 this.cursor = L-1;
85 this.lastMove = (L > 0 ? this.moves[L-1] : null);
86 },
a6088c90
BA
87 setEndgameMessage: function(score) {
88 let eogMessage = "Undefined";
89 switch (score)
90 {
91 case "1-0":
92 eogMessage = translations["White win"];
93 break;
94 case "0-1":
95 eogMessage = translations["Black win"];
96 break;
97 case "1/2":
98 eogMessage = translations["Draw"];
99 break;
100 case "?":
101 eogMessage = "Unfinished";
102 break;
103 }
104 this.endgameMessage = eogMessage;
105 },
106 download: function() {
107 const content = this.getPgn();
108 // Prepare and trigger download link
109 let downloadAnchor = document.getElementById("download");
110 downloadAnchor.setAttribute("download", "game.pgn");
111 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
112 downloadAnchor.click();
113 },
114 getPgn: function() {
115 let pgn = "";
116 pgn += '[Site "vchess.club"]\n';
834c202a 117 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 118 pgn += '[Date "' + getDate(new Date()) + '"]\n';
834c202a
BA
119 pgn += '[White "' + this.game.players[0] + '"]\n';
120 pgn += '[Black "' + this.game.players[1] + '"]\n';
121 pgn += '[Fen "' + this.game.fenStart + '"]\n';
a6088c90
BA
122 pgn += '[Result "' + this.score + '"]\n\n';
123 let counter = 1;
124 let i = 0;
125 while (i < this.moves.length)
126 {
127 pgn += (counter++) + ".";
128 for (let color of ["w","b"])
129 {
130 let move = "";
131 while (i < this.moves.length && this.moves[i].color == color)
132 move += this.moves[i++].notation[0] + ",";
133 move = move.slice(0,-1); //remove last comma
134 pgn += move + (i < this.moves.length-1 ? " " : "");
135 }
136 }
137 return pgn + "\n";
138 },
139 showScoreMsg: function(score) {
140 this.setEndgameMessage(score);
4494c17c 141 let modalBox = document.getElementById("modalEog");
a6088c90
BA
142 modalBox.checked = true;
143 setTimeout(() => { modalBox.checked = false; }, 2000);
144 },
145 endGame: function(score) {
146 this.score = score;
147 this.showScoreMsg(score);
b4fb1612 148 this.$emit("gameover", score);
a6088c90
BA
149 },
150 animateMove: function(move) {
151 let startSquare = document.getElementById(getSquareId(move.start));
152 let endSquare = document.getElementById(getSquareId(move.end));
153 let rectStart = startSquare.getBoundingClientRect();
154 let rectEnd = endSquare.getBoundingClientRect();
155 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
156 let movingPiece =
157 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
158 // HACK for animation (with positive translate, image slides "under background")
159 // Possible improvement: just alter squares on the piece's way...
160 const squares = document.getElementsByClassName("board");
161 for (let i=0; i<squares.length; i++)
162 {
163 let square = squares.item(i);
164 if (square.id != getSquareId(move.start))
165 square.style.zIndex = "-1";
166 }
167 movingPiece.style.transform = "translate(" + translation.x + "px," +
168 translation.y + "px)";
169 movingPiece.style.transitionDuration = "0.2s";
170 movingPiece.style.zIndex = "3000";
171 setTimeout( () => {
172 for (let i=0; i<squares.length; i++)
173 squares.item(i).style.zIndex = "auto";
174 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
175 this.play(move);
176 }, 250);
177 },
c4f91d3f 178 play: function(move, receive, noanimate) {
9d54ab89 179 const navigate = !move;
a6088c90
BA
180 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
181 // (except if we receive opponent's move, human or computer)
c4f91d3f 182 if (!navigate && !this.analyze && !receive
a6088c90
BA
183 && this.cursor < this.moves.length-1)
184 {
185 return;
186 }
187 if (navigate)
188 {
189 if (this.cursor == this.moves.length-1)
190 return; //no more moves
191 move = this.moves[this.cursor+1];
192 }
c4f91d3f 193 if (!!receive && !noanimate) //opponent move, variant != "Dark"
a6088c90
BA
194 {
195 if (this.cursor < this.moves.length-1)
196 this.gotoEnd(); //required to play the move
197 return this.animateMove(move);
198 }
c4f91d3f
BA
199 if (!navigate)
200 {
201 move.color = this.vr.turn;
202 move.notation = this.vr.getNotation(move);
203 }
a6088c90 204 // Not programmatic, or animation is over
a6088c90
BA
205 this.vr.play(move);
206 this.cursor++;
207 this.lastMove = move;
a6088c90
BA
208 if (this.st.settings.sound == 2)
209 new Audio("/sounds/move.mp3").play().catch(err => {});
9d54ab89 210 if (!navigate)
a6088c90 211 {
9d54ab89
BA
212 move.fen = this.vr.getFen();
213 if (this.score == "*" || this.analyze)
214 {
215 // Stack move on movesList at current cursor
216 if (this.cursor == this.moves.length)
217 this.moves.push(move);
218 else
219 this.moves = this.moves.slice(0,this.cursor).concat([move]);
220 }
a6088c90
BA
221 }
222 // Is opponent in check?
223 this.incheck = this.vr.getCheckSquares(this.vr.turn);
224 const score = this.vr.getCurrentScore();
225 if (score != "*")
226 {
227 if (!this.analyze)
228 this.endGame(score);
229 else //just show score on screen (allow undo)
230 this.showScoreMsg(score);
231 }
4494c17c
BA
232 if (!this.analyze)
233 this.$emit("newmove", move); //post-processing (e.g. computer play)
a6088c90
BA
234 },
235 undo: function(move) {
9d54ab89 236 const navigate = !move;
a6088c90
BA
237 if (navigate)
238 {
239 if (this.cursor < 0)
240 return; //no more moves
241 move = this.moves[this.cursor];
242 }
243 this.vr.undo(move);
244 this.cursor--;
245 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
246 if (this.st.settings.sound == 2)
247 new Audio("/sounds/undo.mp3").play().catch(err => {});
248 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4494c17c 249 if (!navigate)
a6088c90
BA
250 this.moves.pop();
251 },
252 gotoMove: function(index) {
37cdcbf3 253 this.vr.re_init(this.moves[index].fen);
a6088c90
BA
254 this.cursor = index;
255 this.lastMove = this.moves[index];
256 },
257 gotoBegin: function() {
834c202a 258 this.vr.re_init(this.game.fenStart);
a6088c90
BA
259 this.cursor = -1;
260 this.lastMove = null;
261 },
262 gotoEnd: function() {
263 this.gotoMove(this.moves.length-1);
264 },
265 flip: function() {
266 this.orientation = V.GetNextCol(this.orientation);
267 },
268 },
269};
270</script>