Complete GameStorage.update. TODO: move transmission
[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 Board(:vr="vr" :last-move="lastMove" :analyze="game.mode=='analyze'"
10 :user-color="game.mycolor" :orientation="orientation"
11 :vname="game.vname" @play-move="play")
12 .button-group
13 button(@click="() => play()") Play
14 button(@click="() => undo()") Undo
15 button(@click="flip") Flip
16 button(@click="gotoBegin") GotoBegin
17 button(@click="gotoEnd") GotoEnd
18 #fenDiv.section-content(v-if="showFen && !!vr")
19 p#fenString.text-center {{ vr.getFen() }}
20 #pgnDiv.section-content
21 a#download(href="#")
22 .button-group
23 button#downloadBtn(@click="download") {{ st.tr["Download PGN"] }}
24 button Import game
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
35 export default {
36 name: 'my-base-game',
37 components: {
38 Board,
39 //MoveList,
40 },
41 // "vr": VariantRules object, describing the game state + rules
42 props: ["vr","game"],
43 data: function() {
44 return {
45 st: store.state,
46 // NOTE: all following variables must be reset at the beginning of a game
47 endgameMessage: "",
48 orientation: "w",
49 score: "*", //'*' means 'unfinished'
50 moves: [],
51 cursor: -1, //index of the move just played
52 lastMove: null,
53 };
54 },
55 watch: {
56 // game initial FEN changes when a new game starts
57 "game.fenStart": function() {
58 this.re_setVariables();
59 },
60 },
61 computed: {
62 showMoves: function() {
63 return true;
64 //return window.innerWidth >= 768;
65 },
66 showFen: function() {
67 return this.game.vname != "Dark" || this.score != "*";
68 },
69 analyze: function() {
70 return this.game.mode == "analyze";
71 },
72 },
73 created: function() {
74 if (!!this.game.fenStart)
75 this.re_setVariables();
76 },
77 methods: {
78 re_setVariables: function() {
79 this.endgameMessage = "";
80 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
81 this.score = this.game.score || "*"; //mutable (if initially "*")
82 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
83 const L = this.moves.length;
84 this.cursor = L-1;
85 this.lastMove = (L > 0 ? this.moves[L-1] : null);
86 },
87 setEndgameMessage: function(score) {
88 let eogMessage = "Undefined";
89 switch (score)
90 {
91 case "1-0":
92 eogMessage = translations["White win"];
93 break;
94 case "0-1":
95 eogMessage = translations["Black win"];
96 break;
97 case "1/2":
98 eogMessage = translations["Draw"];
99 break;
100 case "?":
101 eogMessage = "Unfinished";
102 break;
103 }
104 this.endgameMessage = eogMessage;
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] + '"]\n';
120 pgn += '[Black "' + this.game.players[1] + '"]\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[0] + ",";
133 move = move.slice(0,-1); //remove last comma
134 pgn += move + (i < this.moves.length-1 ? " " : "");
135 }
136 }
137 return pgn + "\n";
138 },
139 showScoreMsg: function(score) {
140 this.setEndgameMessage(score);
141 let modalBox = document.getElementById("modalEog");
142 modalBox.checked = true;
143 setTimeout(() => { modalBox.checked = false; }, 2000);
144 },
145 endGame: function(score) {
146 this.score = score;
147 this.showScoreMsg(score);
148 this.$emit("gameover", score);
149 },
150 animateMove: function(move) {
151 let startSquare = document.getElementById(getSquareId(move.start));
152 let endSquare = document.getElementById(getSquareId(move.end));
153 let rectStart = startSquare.getBoundingClientRect();
154 let rectEnd = endSquare.getBoundingClientRect();
155 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
156 let movingPiece =
157 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
158 // HACK for animation (with positive translate, image slides "under background")
159 // Possible improvement: just alter squares on the piece's way...
160 const squares = document.getElementsByClassName("board");
161 for (let i=0; i<squares.length; i++)
162 {
163 let square = squares.item(i);
164 if (square.id != getSquareId(move.start))
165 square.style.zIndex = "-1";
166 }
167 movingPiece.style.transform = "translate(" + translation.x + "px," +
168 translation.y + "px)";
169 movingPiece.style.transitionDuration = "0.2s";
170 movingPiece.style.zIndex = "3000";
171 setTimeout( () => {
172 for (let i=0; i<squares.length; i++)
173 squares.item(i).style.zIndex = "auto";
174 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
175 this.play(move);
176 }, 250);
177 },
178 play: function(move, programmatic) {
179 const navigate = !move;
180 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
181 // (except if we receive opponent's move, human or computer)
182 if (!navigate && !this.analyze && !programmatic
183 && this.cursor < this.moves.length-1)
184 {
185 return;
186 }
187 if (navigate)
188 {
189 if (this.cursor == this.moves.length-1)
190 return; //no more moves
191 move = this.moves[this.cursor+1];
192 }
193 else
194 {
195 move.color = this.vr.turn;
196 move.notation = this.vr.getNotation(move);
197 }
198 if (!!programmatic) //computer or (remote) human opponent
199 {
200 if (this.cursor < this.moves.length-1)
201 this.gotoEnd(); //required to play the move
202 return this.animateMove(move);
203 }
204 // Not programmatic, or animation is over
205 this.vr.play(move);
206 this.cursor++;
207 this.lastMove = move;
208 if (this.st.settings.sound == 2)
209 new Audio("/sounds/move.mp3").play().catch(err => {});
210 if (!navigate)
211 {
212 move.fen = this.vr.getFen();
213 if (this.score == "*" || this.analyze)
214 {
215 // Stack move on movesList at current cursor
216 if (this.cursor == this.moves.length)
217 this.moves.push(move);
218 else
219 this.moves = this.moves.slice(0,this.cursor).concat([move]);
220 }
221 }
222 // Is opponent in check?
223 this.incheck = this.vr.getCheckSquares(this.vr.turn);
224 const score = this.vr.getCurrentScore();
225 if (score != "*")
226 {
227 if (!this.analyze)
228 this.endGame(score);
229 else //just show score on screen (allow undo)
230 this.showScoreMsg(score);
231 }
232 if (!this.analyze)
233 this.$emit("newmove", move); //post-processing (e.g. computer play)
234 },
235 undo: function(move) {
236 const navigate = !move;
237 if (navigate)
238 {
239 if (this.cursor < 0)
240 return; //no more moves
241 move = this.moves[this.cursor];
242 }
243 this.vr.undo(move);
244 this.cursor--;
245 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
246 if (this.st.settings.sound == 2)
247 new Audio("/sounds/undo.mp3").play().catch(err => {});
248 this.incheck = this.vr.getCheckSquares(this.vr.turn);
249 if (!navigate)
250 this.moves.pop();
251 },
252 gotoMove: function(index) {
253 this.vr.re_init(this.moves[index].fen);
254 this.cursor = index;
255 this.lastMove = this.moves[index];
256 },
257 gotoBegin: function() {
258 this.vr.re_init(this.game.fenStart);
259 this.cursor = -1;
260 this.lastMove = null;
261 },
262 gotoEnd: function() {
263 this.gotoMove(this.moves.length-1);
264 },
265 flip: function() {
266 this.orientation = V.GetNextCol(this.orientation);
267 },
268 },
269 };
270 </script>