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