5ee5e0c72ae9d9d1bb2ff2072f61d5f26ab0d9da
[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 let 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 if (!!programmatic) //computer or (remote) human opponent
194 {
195 if (this.cursor < this.moves.length-1)
196 this.gotoEnd(); //required to play the move
197 return this.animateMove(move);
198 }
199 // Not programmatic, or animation is over
200 if (!move.notation)
201 move.notation = this.vr.getNotation(move);
202 if (!move.color)
203 move.color = this.vr.turn;
204 this.vr.play(move);
205 this.cursor++;
206 this.lastMove = move;
207 if (!move.fen)
208 move.fen = this.vr.getFen();
209 if (this.st.settings.sound == 2)
210 new Audio("/sounds/move.mp3").play().catch(err => {});
211 if (!navigate && (this.score == "*" || this.analyze))
212 {
213 // Stack move on movesList at current cursor
214 if (this.cursor == this.moves.length)
215 this.moves.push(move);
216 else
217 this.moves = this.moves.slice(0,this.cursor).concat([move]);
218 }
219 // Is opponent in check?
220 this.incheck = this.vr.getCheckSquares(this.vr.turn);
221 const score = this.vr.getCurrentScore();
222 if (score != "*")
223 {
224 if (!this.analyze)
225 this.endGame(score);
226 else //just show score on screen (allow undo)
227 this.showScoreMsg(score);
228 }
229 if (!this.analyze)
230 this.$emit("newmove", move); //post-processing (e.g. computer play)
231 },
232 undo: function(move) {
233 let navigate = !move;
234 if (navigate)
235 {
236 if (this.cursor < 0)
237 return; //no more moves
238 move = this.moves[this.cursor];
239 }
240 this.vr.undo(move);
241 this.cursor--;
242 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
243 if (this.st.settings.sound == 2)
244 new Audio("/sounds/undo.mp3").play().catch(err => {});
245 this.incheck = this.vr.getCheckSquares(this.vr.turn);
246 if (!navigate)
247 this.moves.pop();
248 },
249 gotoMove: function(index) {
250 this.vr.re_init(this.moves[index].fen);
251 this.cursor = index;
252 this.lastMove = this.moves[index];
253 },
254 gotoBegin: function() {
255 this.vr.re_init(this.game.fenStart);
256 this.cursor = -1;
257 this.lastMove = null;
258 },
259 gotoEnd: function() {
260 this.gotoMove(this.moves.length-1);
261 },
262 flip: function() {
263 this.orientation = V.GetNextCol(this.orientation);
264 },
265 },
266 };
267 </script>