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