'update'
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90 1<template lang="pug">
dcd68c41
BA
2div#baseGame(tabindex=-1 @click="() => focusBg()"
3 @keydown="handleKeys" @wheel="handleScroll")
7e355d68 4 input#modalEog.modal(type="checkbox")
dcd68c41 5 div(role="dialog" data-checkbox="modalEog" aria-labelledby="eogMessage")
7e355d68
BA
6 .card.smallpad.small-modal.text-center
7 label.modal-close(for="modalEog")
8 h3#eogMessage.section {{ endgameMessage }}
cf94b843
BA
9 #gameContainer
10 #boardContainer
11 Board(:vr="vr" :last-move="lastMove" :analyze="game.mode=='analyze'"
12 :user-color="game.mycolor" :orientation="orientation"
13 :vname="game.vname" @play-move="play")
0e16cb26
BA
14 #turnIndicator(v-if="game.vname=='Dark' && game.mode!='analyze'")
15 | {{ turn }}
cf94b843
BA
16 #controls
17 button(@click="gotoBegin") <<
18 button(@click="() => undo()") <
19 button(@click="flip") &#8645;
20 button(@click="() => play()") >
21 button(@click="gotoEnd") >>
22 #pgnDiv
23 a#download(href="#")
24 button(@click="download") {{ st.tr["Download PGN"] }}
0e16cb26
BA
25 button(v-if="game.vname!='Dark' && game.mode!='analyze'"
26 @click="analyzePosition")
cf94b843 27 | {{ st.tr["Analyze"] }}
0e16cb26 28 button(@click="showRules") {{ st.tr["Rules"] }}
cf94b843 29 #movesList
430a2038 30 MoveList(v-if="showMoves" :score="game.score" :message="game.scoreMsg"
5157ce0b
BA
31 :firstNum="firstMoveNumber" :moves="moves" :cursor="cursor"
32 @goto-move="gotoMove")
41c80bb6 33 .clearer
a6088c90
BA
34</template>
35
36<script>
37import Board from "@/components/Board.vue";
f21cd6d9 38import MoveList from "@/components/MoveList.vue";
a6088c90
BA
39import { store } from "@/store";
40import { getSquareId } from "@/utils/squareId";
d4036efe 41import { getDate } from "@/utils/datetime";
a6088c90
BA
42
43export default {
44 name: 'my-base-game',
45 components: {
46 Board,
f21cd6d9 47 MoveList,
a6088c90 48 },
bc8734ba 49 // "vr": VariantRules object, describing the game state + rules
834c202a 50 props: ["vr","game"],
a6088c90
BA
51 data: function() {
52 return {
53 st: store.state,
b7c32f1a 54 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
55 endgameMessage: "",
56 orientation: "w",
57 score: "*", //'*' means 'unfinished'
b7c32f1a 58 moves: [],
a6088c90
BA
59 cursor: -1, //index of the move just played
60 lastMove: null,
5157ce0b 61 firstMoveNumber: 0, //for printing
a6088c90
BA
62 };
63 },
37cdcbf3 64 watch: {
834c202a
BA
65 // game initial FEN changes when a new game starts
66 "game.fenStart": function() {
4b0384fa 67 this.re_setVariables();
37cdcbf3 68 },
7e355d68 69 // Received a new move to play:
63ca2b89
BA
70 "game.moveToPlay": function(newMove) {
71 if (!!newMove) //if stop + launch new game, get undefined move
72 this.play(newMove, "receive");
7e355d68 73 },
37cdcbf3 74 },
a6088c90
BA
75 computed: {
76 showMoves: function() {
63ca2b89 77 return this.game.vname != "Dark" || this.game.mode=="analyze";
a6088c90 78 },
0e16cb26
BA
79 turn: function() {
80 let color = "";
81 const L = this.moves.length;
82 if (L == 0 || this.moves[L-1].color == "b")
83 color = "White";
84 else //if (this.moves[L-1].color == "w")
85 color = "Black";
86 return color + " turn";
87 },
a6088c90 88 },
4b0384fa
BA
89 created: function() {
90 if (!!this.game.fenStart)
91 this.re_setVariables();
92 },
cf94b843 93 mounted: function() {
96e9585a
BA
94 // Take full width on small screens:
95 let boardSize = parseInt(localStorage.getItem("boardSize"));
96 if (!boardSize)
97 {
98 boardSize = (window.innerWidth >= 768
99 ? Math.min(600, 0.5*window.innerWidth) //heuristic...
100 : window.innerWidth);
101 }
102 const movesWidth = (window.innerWidth >= 768 ? 280 : 0);
103 document.getElementById("boardContainer").style.width = boardSize + "px";
104 let gameContainer = document.getElementById("gameContainer");
105 gameContainer.style.width = (boardSize + movesWidth) + "px";
cf94b843 106 },
a6088c90 107 methods: {
9ca1e26b 108 focusBg: function() {
41c80bb6 109 // NOTE: small blue border appears...
9ca1e26b
BA
110 document.getElementById("baseGame").focus();
111 },
112 handleKeys: function(e) {
5701c228
BA
113 if ([32,37,38,39,40].includes(e.keyCode))
114 e.preventDefault();
9ca1e26b
BA
115 switch (e.keyCode)
116 {
117 case 37:
118 this.undo();
119 break;
120 case 39:
121 this.play();
122 break;
5701c228 123 case 38:
9ca1e26b
BA
124 this.gotoBegin();
125 break;
126 case 40:
127 this.gotoEnd();
128 break;
129 case 32:
9ca1e26b
BA
130 this.flip();
131 break;
132 }
133 },
dcd68c41 134 handleScroll: function(e) {
41c80bb6
BA
135 if (this.game.mode == "analyze" || this.game.score != "*")
136 {
137 e.preventDefault();
138 if (e.deltaY < 0)
139 this.undo();
140 else if (e.deltaY > 0)
141 this.play();
142 }
dcd68c41 143 },
0e16cb26
BA
144 showRules: function() {
145 //this.$router.push("/variants/" + this.game.vname);
146 window.open("#/variants/" + this.game.vname, "_blank"); //better
147 },
4b0384fa
BA
148 re_setVariables: function() {
149 this.endgameMessage = "";
150 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
4b0384fa 151 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
d4036efe
BA
152 // Post-processing: decorate each move with color + current FEN:
153 // (to be able to jump to any position quickly)
27d18a24 154 let vr_tmp = new V(this.game.fenStart); //vr is already at end of game
5157ce0b
BA
155 this.firstMoveNumber =
156 Math.floor(V.ParseFen(this.game.fenStart).movesCount / 2);
d4036efe
BA
157 this.moves.forEach(move => {
158 // NOTE: this is doing manually what play() function below achieve,
159 // but in a lighter "fast-forward" way
27d18a24
BA
160 move.color = vr_tmp.turn;
161 move.notation = vr_tmp.getNotation(move);
162 vr_tmp.play(move);
163 move.fen = vr_tmp.getFen();
d4036efe 164 });
697ee580
BA
165 if (this.game.fenStart.indexOf(" b ") >= 0 ||
166 (this.moves.length > 0 && this.moves[0].color == "b"))
167 {
168 // 'end' is required for Board component to check lastMove for e.p.
169 this.moves.unshift({color: "w", notation: "...", end: {x:-1,y:-1}});
170 }
4b0384fa
BA
171 const L = this.moves.length;
172 this.cursor = L-1;
173 this.lastMove = (L > 0 ? this.moves[L-1] : null);
174 },
63ca2b89
BA
175 analyzePosition: function() {
176 const newUrl = "/analyze/" + this.game.vname +
177 "/?fen=" + this.vr.getFen().replace(/ /g, "_");
0e16cb26
BA
178 if (this.game.type == "live")
179 this.$router.push(newUrl); //open in same tab: against cheating...
180 else
181 window.open("#" + newUrl); //open in a new tab: more comfortable
603b8a8b 182 },
a6088c90
BA
183 download: function() {
184 const content = this.getPgn();
185 // Prepare and trigger download link
186 let downloadAnchor = document.getElementById("download");
187 downloadAnchor.setAttribute("download", "game.pgn");
188 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
189 downloadAnchor.click();
190 },
191 getPgn: function() {
192 let pgn = "";
193 pgn += '[Site "vchess.club"]\n';
834c202a 194 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 195 pgn += '[Date "' + getDate(new Date()) + '"]\n';
d4036efe
BA
196 pgn += '[White "' + this.game.players[0].name + '"]\n';
197 pgn += '[Black "' + this.game.players[1].name + '"]\n';
834c202a 198 pgn += '[Fen "' + this.game.fenStart + '"]\n';
430a2038 199 pgn += '[Result "' + this.game.score + '"]\n\n';
a6088c90
BA
200 let counter = 1;
201 let i = 0;
202 while (i < this.moves.length)
203 {
204 pgn += (counter++) + ".";
205 for (let color of ["w","b"])
206 {
207 let move = "";
208 while (i < this.moves.length && this.moves[i].color == color)
d4036efe 209 move += this.moves[i++].notation + ",";
a6088c90 210 move = move.slice(0,-1); //remove last comma
d4036efe 211 pgn += move + (i < this.moves.length ? " " : "");
a6088c90
BA
212 }
213 }
214 return pgn + "\n";
215 },
b988c726
BA
216 getScoreMessage: function(score) {
217 let eogMessage = "Undefined";
218 switch (score)
219 {
220 case "1-0":
221 eogMessage = this.st.tr["White win"];
222 break;
223 case "0-1":
224 eogMessage = this.st.tr["Black win"];
225 break;
226 case "1/2":
227 eogMessage = this.st.tr["Draw"];
228 break;
229 case "?":
230 eogMessage = this.st.tr["Unfinished"];
231 break;
232 }
233 return eogMessage;
234 },
235 showEndgameMsg: function(message) {
236 this.endgameMessage = message;
4494c17c 237 let modalBox = document.getElementById("modalEog");
a6088c90
BA
238 modalBox.checked = true;
239 setTimeout(() => { modalBox.checked = false; }, 2000);
240 },
63ca2b89 241 animateMove: function(move, callback) {
a6088c90
BA
242 let startSquare = document.getElementById(getSquareId(move.start));
243 let endSquare = document.getElementById(getSquareId(move.end));
244 let rectStart = startSquare.getBoundingClientRect();
245 let rectEnd = endSquare.getBoundingClientRect();
246 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
247 let movingPiece =
248 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
249 // HACK for animation (with positive translate, image slides "under background")
250 // Possible improvement: just alter squares on the piece's way...
251 const squares = document.getElementsByClassName("board");
252 for (let i=0; i<squares.length; i++)
253 {
254 let square = squares.item(i);
255 if (square.id != getSquareId(move.start))
256 square.style.zIndex = "-1";
257 }
258 movingPiece.style.transform = "translate(" + translation.x + "px," +
259 translation.y + "px)";
260 movingPiece.style.transitionDuration = "0.2s";
261 movingPiece.style.zIndex = "3000";
262 setTimeout( () => {
263 for (let i=0; i<squares.length; i++)
264 squares.item(i).style.zIndex = "auto";
265 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
63ca2b89 266 callback();
a6088c90
BA
267 }, 250);
268 },
63ca2b89
BA
269 play: function(move, receive) {
270 // NOTE: navigate and receive are mutually exclusive
9d54ab89 271 const navigate = !move;
63ca2b89
BA
272 // Forbid playing outside analyze mode, except if move is received.
273 // Sufficient condition because Board already knows which turn it is.
274 if (!navigate && this.game.mode!="analyze" && !receive
a6088c90
BA
275 && this.cursor < this.moves.length-1)
276 {
277 return;
278 }
63ca2b89
BA
279 const doPlayMove = () => {
280 if (!!receive && this.cursor < this.moves.length-1)
a6088c90 281 this.gotoEnd(); //required to play the move
63ca2b89
BA
282 if (navigate)
283 {
284 if (this.cursor == this.moves.length-1)
285 return; //no more moves
286 move = this.moves[this.cursor+1];
287 }
288 else
9d54ab89 289 {
63ca2b89
BA
290 move.color = this.vr.turn;
291 move.notation = this.vr.getNotation(move);
292 }
293 this.vr.play(move);
294 this.cursor++;
295 this.lastMove = move;
296 if (this.st.settings.sound == 2)
297 new Audio("/sounds/move.mp3").play().catch(err => {});
298 if (!navigate)
299 {
300 move.fen = this.vr.getFen();
9d54ab89
BA
301 // Stack move on movesList at current cursor
302 if (this.cursor == this.moves.length)
303 this.moves.push(move);
304 else
305 this.moves = this.moves.slice(0,this.cursor).concat([move]);
306 }
0e16cb26 307 if (!navigate && this.game.mode!="analyze")
63ca2b89
BA
308 this.$emit("newmove", move); //post-processing (e.g. computer play)
309 // Is opponent in check?
310 this.incheck = this.vr.getCheckSquares(this.vr.turn);
311 const score = this.vr.getCurrentScore();
312 if (score != "*")
313 {
314 const message = this.getScoreMessage(score);
315 if (this.game.mode != "analyze")
316 this.$emit("gameover", score, message);
317 else //just show score on screen (allow undo)
318 this.showEndgameMsg(score + " . " + message);
319 }
320 };
321 if (!!receive && this.game.vname != "Dark")
322 this.animateMove(move, doPlayMove);
323 else
324 doPlayMove();
a6088c90
BA
325 },
326 undo: function(move) {
9d54ab89 327 const navigate = !move;
a6088c90
BA
328 if (navigate)
329 {
330 if (this.cursor < 0)
331 return; //no more moves
332 move = this.moves[this.cursor];
333 }
334 this.vr.undo(move);
335 this.cursor--;
336 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
337 if (this.st.settings.sound == 2)
338 new Audio("/sounds/undo.mp3").play().catch(err => {});
339 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4494c17c 340 if (!navigate)
a6088c90
BA
341 this.moves.pop();
342 },
343 gotoMove: function(index) {
37cdcbf3 344 this.vr.re_init(this.moves[index].fen);
a6088c90
BA
345 this.cursor = index;
346 this.lastMove = this.moves[index];
347 },
348 gotoBegin: function() {
5157ce0b
BA
349 if (this.cursor == -1)
350 return;
834c202a 351 this.vr.re_init(this.game.fenStart);
5701c228
BA
352 if (this.moves.length > 0 && this.moves[0].notation == "...")
353 {
354 this.cursor = 0;
355 this.lastMove = this.moves[0];
356 }
357 else
358 {
359 this.cursor = -1;
360 this.lastMove = null;
361 }
a6088c90
BA
362 },
363 gotoEnd: function() {
5157ce0b
BA
364 if (this.cursor == this.moves.length - 1)
365 return;
a6088c90
BA
366 this.gotoMove(this.moves.length-1);
367 },
368 flip: function() {
0e16cb26 369 this.orientation = V.GetOppCol(this.orientation);
a6088c90
BA
370 },
371 },
372};
373</script>
72ccbd67 374
41c80bb6 375<style lang="sass" scoped>
cf94b843
BA
376#baseGame
377 width: 100%
378
379#gameContainer
72ccbd67
BA
380 margin-left: auto
381 margin-right: auto
cf94b843
BA
382
383#modal-eog+div .card
384 overflow: hidden
72ccbd67
BA
385#controls
386 margin-top: 10px
cf94b843
BA
387 margin-left: auto
388 margin-right: auto
72ccbd67
BA
389 button
390 display: inline-block
391 width: 20%
392 margin: 0
41c80bb6
BA
393@media screen and (min-width: 768px)
394 #controls
395 max-width: 400px
0e16cb26
BA
396#turnIndicator
397 text-align: center
cf94b843
BA
398#pgnDiv
399 text-align: center
400 margin-left: auto
401 margin-right: auto
72ccbd67 402#boardContainer
cf94b843 403 float: left
41c80bb6
BA
404// TODO: later, maybe, allow movesList of variable width
405// or e.g. between 250 and 350px (but more complicated)
cf94b843
BA
406#movesList
407 width: 280px
408 float: left
96e9585a
BA
409@media screen and (max-width: 767px)
410 #movesList
411 width: 100%
412 float: none
413 clear: both
72ccbd67 414</style>