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