Fix clocks update
[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
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"] }}
d4036efe
BA
25 // TODO: Import game button copy game locally in IndexedDB
26 //button Import game
a6088c90
BA
27 //MoveList(v-if="showMoves"
28 :moves="moves" :cursor="cursor" @goto-move="gotoMove")
29</template>
30
31<script>
32import Board from "@/components/Board.vue";
33//import MoveList from "@/components/MoveList.vue";
34import { store } from "@/store";
35import { getSquareId } from "@/utils/squareId";
d4036efe 36import { getDate } from "@/utils/datetime";
a6088c90
BA
37
38export default {
39 name: 'my-base-game',
40 components: {
41 Board,
42 //MoveList,
43 },
bc8734ba 44 // "vr": VariantRules object, describing the game state + rules
834c202a 45 props: ["vr","game"],
a6088c90
BA
46 data: function() {
47 return {
48 st: store.state,
b7c32f1a 49 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
50 endgameMessage: "",
51 orientation: "w",
52 score: "*", //'*' means 'unfinished'
b7c32f1a 53 moves: [],
a6088c90
BA
54 cursor: -1, //index of the move just played
55 lastMove: null,
56 };
57 },
37cdcbf3 58 watch: {
834c202a
BA
59 // game initial FEN changes when a new game starts
60 "game.fenStart": function() {
4b0384fa 61 this.re_setVariables();
37cdcbf3
BA
62 },
63 },
a6088c90
BA
64 computed: {
65 showMoves: function() {
66 return true;
67 //return window.innerWidth >= 768;
68 },
69 showFen: function() {
834c202a
BA
70 return this.game.vname != "Dark" || this.score != "*";
71 },
72 analyze: function() {
d4036efe 73 return this.game.mode == "analyze" || this.game.score != "*";
a6088c90
BA
74 },
75 },
4b0384fa
BA
76 created: function() {
77 if (!!this.game.fenStart)
78 this.re_setVariables();
79 },
a6088c90 80 methods: {
4b0384fa
BA
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 || []));
d4036efe
BA
86 // Post-processing: decorate each move with color + current FEN:
87 // (to be able to jump to any position quickly)
27d18a24 88 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
d4036efe
BA
89 this.moves.forEach(move => {
90 // NOTE: this is doing manually what play() function below achieve,
91 // but in a lighter "fast-forward" way
27d18a24
BA
92 move.color = vr_tmp.turn;
93 move.notation = vr_tmp.getNotation(move);
94 vr_tmp.play(move);
95 move.fen = vr_tmp.getFen();
d4036efe 96 });
4b0384fa
BA
97 const L = this.moves.length;
98 this.cursor = L-1;
99 this.lastMove = (L > 0 ? this.moves[L-1] : null);
100 },
a6088c90
BA
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';
834c202a 112 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 113 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
114 pgn += '[White "' + this.game.players[0].name + '"]\n';
115 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 116 pgn += '[Fen "' + this.game.fenStart + '"]\n';
a6088c90
BA
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)
d4036efe 127 move += this.moves[i++].notation + ",";
a6088c90 128 move = move.slice(0,-1); //remove last comma
d4036efe 129 pgn += move + (i < this.moves.length ? " " : "");
a6088c90
BA
130 }
131 }
132 return pgn + "\n";
133 },
b988c726
BA
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;
4494c17c 155 let modalBox = document.getElementById("modalEog");
a6088c90
BA
156 modalBox.checked = true;
157 setTimeout(() => { modalBox.checked = false; }, 2000);
158 },
b988c726 159 endGame: function(score, message) {
a6088c90 160 this.score = score;
b988c726
BA
161 if (!message)
162 message = this.getScoreMessage(score);
163 this.showEndgameMsg(score + " . " + message);
b4fb1612 164 this.$emit("gameover", score);
a6088c90
BA
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 },
c4f91d3f 194 play: function(move, receive, noanimate) {
9d54ab89 195 const navigate = !move;
a6088c90
BA
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)
c4f91d3f 198 if (!navigate && !this.analyze && !receive
a6088c90
BA
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 }
c4f91d3f 209 if (!!receive && !noanimate) //opponent move, variant != "Dark"
a6088c90
BA
210 {
211 if (this.cursor < this.moves.length-1)
212 this.gotoEnd(); //required to play the move
213 return this.animateMove(move);
214 }
c4f91d3f
BA
215 if (!navigate)
216 {
217 move.color = this.vr.turn;
218 move.notation = this.vr.getNotation(move);
219 }
a6088c90 220 // Not programmatic, or animation is over
a6088c90
BA
221 this.vr.play(move);
222 this.cursor++;
223 this.lastMove = move;
a6088c90
BA
224 if (this.st.settings.sound == 2)
225 new Audio("/sounds/move.mp3").play().catch(err => {});
9d54ab89 226 if (!navigate)
a6088c90 227 {
9d54ab89
BA
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 }
a6088c90 237 }
93d1d7a7 238 // Is opponent in check? (TODO: generalize, find all check squares)
a6088c90
BA
239 this.incheck = this.vr.getCheckSquares(this.vr.turn);
240 const score = this.vr.getCurrentScore();
93d1d7a7 241 if (score != "*") //TODO: generalize score for 3 or 4 players
a6088c90
BA
242 {
243 if (!this.analyze)
244 this.endGame(score);
b988c726
BA
245 else
246 {
247 // Just show score on screen (allow undo)
248 const message = this.getScoreMessage(score);
249 this.showEndgameMsg(score + " . " + message);
250 }
a6088c90 251 }
4494c17c
BA
252 if (!this.analyze)
253 this.$emit("newmove", move); //post-processing (e.g. computer play)
a6088c90
BA
254 },
255 undo: function(move) {
9d54ab89 256 const navigate = !move;
a6088c90
BA
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);
4494c17c 269 if (!navigate)
a6088c90
BA
270 this.moves.pop();
271 },
272 gotoMove: function(index) {
37cdcbf3 273 this.vr.re_init(this.moves[index].fen);
a6088c90
BA
274 this.cursor = index;
275 this.lastMove = this.moves[index];
276 },
277 gotoBegin: function() {
834c202a 278 this.vr.re_init(this.game.fenStart);
a6088c90
BA
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>