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