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