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