Fix. TODO: Vue reactivity on game.score and game. ...
[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 };
55 },
56 watch: {
57 // game initial FEN changes when a new game starts
58 "game.fenStart": function() {
59 this.re_setVariables();
60 },
61 // Received a new move to play:
62 "game.moveToPlay": function() {
63 this.play(this.game.moveToPlay, "receive", this.game.vname=="Dark");
64 },
65 "game.score": function(score) {
66 if (score != "*")
67 this.endGame(score, this.game.scoreMsg);
68 },
69 },
70 computed: {
71 showMoves: function() {
72 return true;
73 //return window.innerWidth >= 768;
74 },
75 showFen: function() {
76 return this.game.vname != "Dark" || this.score != "*";
77 },
78 analyze: function() {
79 return this.game.mode == "analyze" || this.score != "*";
80 },
81 },
82 created: function() {
83 if (!!this.game.fenStart)
84 this.re_setVariables();
85 },
86 methods: {
87 re_setVariables: function() {
88 this.endgameMessage = "";
89 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
90 this.score = this.game.score || "*"; //mutable (if initially "*")
91 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
92 // Post-processing: decorate each move with color + current FEN:
93 // (to be able to jump to any position quickly)
94 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
95 this.moves.forEach(move => {
96 // NOTE: this is doing manually what play() function below achieve,
97 // but in a lighter "fast-forward" way
98 move.color = vr_tmp.turn;
99 move.notation = vr_tmp.getNotation(move);
100 vr_tmp.play(move);
101 move.fen = vr_tmp.getFen();
102 });
103 if (this.game.fenStart.indexOf(" b ") >= 0 ||
104 (this.moves.length > 0 && this.moves[0].color == "b"))
105 {
106 // 'end' is required for Board component to check lastMove for e.p.
107 this.moves.unshift({color: "w", notation: "...", end: {x:-1,y:-1}});
108 }
109 const L = this.moves.length;
110 this.cursor = L-1;
111 this.lastMove = (L > 0 ? this.moves[L-1] : null);
112 },
113 gotoFenContent: function(event) {
114 this.$router.push("/analyze/" + this.game.vname +
115 "/?fen=" + event.target.innerText.replace(/ /g, "_"));
116 },
117 download: function() {
118 const content = this.getPgn();
119 // Prepare and trigger download link
120 let downloadAnchor = document.getElementById("download");
121 downloadAnchor.setAttribute("download", "game.pgn");
122 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
123 downloadAnchor.click();
124 },
125 getPgn: function() {
126 let pgn = "";
127 pgn += '[Site "vchess.club"]\n';
128 pgn += '[Variant "' + this.game.vname + '"]\n';
129 pgn += '[Date "' + getDate(new Date()) + '"]\n';
130 pgn += '[White "' + this.game.players[0].name + '"]\n';
131 pgn += '[Black "' + this.game.players[1].name + '"]\n';
132 pgn += '[Fen "' + this.game.fenStart + '"]\n';
133 pgn += '[Result "' + this.score + '"]\n\n';
134 let counter = 1;
135 let i = 0;
136 while (i < this.moves.length)
137 {
138 pgn += (counter++) + ".";
139 for (let color of ["w","b"])
140 {
141 let move = "";
142 while (i < this.moves.length && this.moves[i].color == color)
143 move += this.moves[i++].notation + ",";
144 move = move.slice(0,-1); //remove last comma
145 pgn += move + (i < this.moves.length ? " " : "");
146 }
147 }
148 return pgn + "\n";
149 },
150 getScoreMessage: function(score) {
151 let eogMessage = "Undefined";
152 switch (score)
153 {
154 case "1-0":
155 eogMessage = this.st.tr["White win"];
156 break;
157 case "0-1":
158 eogMessage = this.st.tr["Black win"];
159 break;
160 case "1/2":
161 eogMessage = this.st.tr["Draw"];
162 break;
163 case "?":
164 eogMessage = this.st.tr["Unfinished"];
165 break;
166 }
167 return eogMessage;
168 },
169 showEndgameMsg: function(message) {
170 this.endgameMessage = message;
171 let modalBox = document.getElementById("modalEog");
172 modalBox.checked = true;
173 setTimeout(() => { modalBox.checked = false; }, 2000);
174 },
175 endGame: function(score, message) {
176 this.score = score;
177 if (!message)
178 message = this.getScoreMessage(score);
179 this.showEndgameMsg(score + " . " + message);
180 this.$emit("gameover", score);
181 },
182 animateMove: function(move) {
183 let startSquare = document.getElementById(getSquareId(move.start));
184 let endSquare = document.getElementById(getSquareId(move.end));
185 let rectStart = startSquare.getBoundingClientRect();
186 let rectEnd = endSquare.getBoundingClientRect();
187 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
188 let movingPiece =
189 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
190 // HACK for animation (with positive translate, image slides "under background")
191 // Possible improvement: just alter squares on the piece's way...
192 const squares = document.getElementsByClassName("board");
193 for (let i=0; i<squares.length; i++)
194 {
195 let square = squares.item(i);
196 if (square.id != getSquareId(move.start))
197 square.style.zIndex = "-1";
198 }
199 movingPiece.style.transform = "translate(" + translation.x + "px," +
200 translation.y + "px)";
201 movingPiece.style.transitionDuration = "0.2s";
202 movingPiece.style.zIndex = "3000";
203 setTimeout( () => {
204 for (let i=0; i<squares.length; i++)
205 squares.item(i).style.zIndex = "auto";
206 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
207 this.play(move);
208 }, 250);
209 },
210 play: function(move, receive, noanimate) {
211 const navigate = !move;
212 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
213 // (except if we receive opponent's move, human or computer)
214 if (!navigate && !this.analyze && !receive
215 && this.cursor < this.moves.length-1)
216 {
217 return;
218 }
219 if (navigate)
220 {
221 if (this.cursor == this.moves.length-1)
222 return; //no more moves
223 move = this.moves[this.cursor+1];
224 }
225 if (!!receive && !noanimate) //opponent move, variant != "Dark"
226 {
227 if (this.cursor < this.moves.length-1)
228 this.gotoEnd(); //required to play the move
229 return this.animateMove(move);
230 }
231 if (!navigate)
232 {
233 move.color = this.vr.turn;
234 move.notation = this.vr.getNotation(move);
235 }
236 // Not programmatic, or animation is over
237 this.vr.play(move);
238 this.cursor++;
239 this.lastMove = move;
240 if (this.st.settings.sound == 2)
241 new Audio("/sounds/move.mp3").play().catch(err => {});
242 if (!navigate)
243 {
244 move.fen = this.vr.getFen();
245 if (this.score == "*" || this.analyze)
246 {
247 // Stack move on movesList at current cursor
248 if (this.cursor == this.moves.length)
249 this.moves.push(move);
250 else
251 this.moves = this.moves.slice(0,this.cursor).concat([move]);
252 }
253 }
254 if (!this.analyze)
255 this.$emit("newmove", move); //post-processing (e.g. computer play)
256 // Is opponent in check?
257 this.incheck = this.vr.getCheckSquares(this.vr.turn);
258 const score = this.vr.getCurrentScore();
259 if (score != "*")
260 {
261 if (!this.analyze)
262 this.endGame(score);
263 else
264 {
265 // Just show score on screen (allow undo)
266 const message = this.getScoreMessage(score);
267 this.showEndgameMsg(score + " . " + message);
268 }
269 }
270 },
271 undo: function(move) {
272 const navigate = !move;
273 if (navigate)
274 {
275 if (this.cursor < 0)
276 return; //no more moves
277 move = this.moves[this.cursor];
278 }
279 this.vr.undo(move);
280 this.cursor--;
281 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
282 if (this.st.settings.sound == 2)
283 new Audio("/sounds/undo.mp3").play().catch(err => {});
284 this.incheck = this.vr.getCheckSquares(this.vr.turn);
285 if (!navigate)
286 this.moves.pop();
287 },
288 gotoMove: function(index) {
289 this.vr.re_init(this.moves[index].fen);
290 this.cursor = index;
291 this.lastMove = this.moves[index];
292 },
293 gotoBegin: function() {
294 this.vr.re_init(this.game.fenStart);
295 this.cursor = -1;
296 this.lastMove = null;
297 },
298 gotoEnd: function() {
299 this.gotoMove(this.moves.length-1);
300 },
301 flip: function() {
302 this.orientation = V.GetNextCol(this.orientation);
303 },
304 },
305 };
306 </script>