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