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