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