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